> On Mar 10, 2018, at 9:34 PM, Robert Phillips <
robert.p...@gmail.com> wrote:
>
> Thanks, that works
>
> When I do create_table (:gars) { |t| t.string :name }
>
> What exactly is that syntax.. Like is the string of t.string, a method of the t object, that takes a symbol?
>
>
>
Here's the nutshell:
Ruby's block syntax may be written two ways. Your example is the one-liner form. You may be used to seeing this:
@whatever.each do |something|
something.do_something
end
That could also be written as
@whatever.each{ |something| something.do_something }
It's just a physically-compact form, it does the same thing in one line as three. To answer your other question, whatever is between the pipes is the object that gets passed into the block. In the case of create_table, it's a method that accepts a block, rather than an iterator (as in my first example) that yields instances to one. If there is an argument before the block, it is optionally inside parentheses (for the multi-line do-end form), and required to be inside parentheses if you're using the one-liner format.
Here's a multi-line block format migration method:
create_table :friendly_id_slugs do |t|
t.string :slug, :null => false
t.integer :sluggable_id, :null => false
t.string :sluggable_type, :limit => 50
t.string :scope
t.datetime :created_at
end
So you have the method create_table(), which is sent one to two arguments: the table name to be created, and a hash of options, and then optionally passed a block with the details of the table. "t" is the name you gave the block, just the same as "something" in my example. The name itself is not significant, but off of that block hangs the rest of the details for create_table to use when making your table. If you don't pass the block, then the table is created without any columns.
https://apidock.com/rails/ActiveRecord/ConnectionAdapters/SchemaStatements/create_table
Walter
> --
> You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to
rubyonrails-ta...@googlegroups.com.
> To post to this group, send email to
rubyonra...@googlegroups.com.
> To view this discussion on the web visit
https://groups.google.com/d/msgid/rubyonrails-talk/79c19806-23ec-4af6-b2e2-e1d590ecea18%40googlegroups.com.
> For more options, visit
https://groups.google.com/d/optout.