Home > Mobile >  Ruby syntax in ActiveRecord
Ruby syntax in ActiveRecord

Time:02-26

I am currently doing the ruby on rails beginner tutorials and I do not understand the specific syntax of migrations.

class CreateArticles < ActiveRecord::Migration[7.0]
  def change
    create_table :articles do |t|
      t.string :title
      t.text :body

      t.timestamps
    end
  end
end

Specifically, I do not understand the syntax within the method change on line 3.

What does create_table refers to?

What does :articles means? Is it a symbol?

What is the |t| in this case referring to. To a new table?

Any context and deeper explanations of this code would be appreciated.

CodePudding user response:

Ruby libraries often use "DSLs" (domain specific languages). This is an example of one, however once you understand Ruby syntax you can see that it is , in fact, just regular Ruby.

You are right that create_table is a method call, and :articles is a symbol.

Also remember that functions in ruby can take block arguments, which have two possible syntaxes:

[1,2,3].each { |num| <block content> }

# or ..
[1,2,3].each do |num|
  <block content>
end

In here |num| is a block argument. Under the hood, each will take the input and pass each element one-by-one to the block. We refer to the current element by this block argument.

So, taking all this into consideration, we can rewrite this function call like so:

create_table(:articles) do |table|
  <do stuff with table>
end

Remember that the parenthesis are usually optional in Ruby, which is why it can be written as create_table :articles

In more plain language, what this is saying is "create a table with the name articles, and then customize that table with the block". It's inside the block that individual columns are added to the table.

I would recommnend reading up more on Ruby blocks since it's a very valuable and important concept.

If you want to write a method that takes a regular argument and a block, it might look like so:

def my_function(symbol)
  yield(symbol)
end

And then calling it:

my_function :some_symbol do |symbol|
  puts "the value is #{symbol}"
end
  • Related