开发者

Ruby grammar question

I'm new to ruby. So I'm confused by the following lines of code:

class CreateProducts < ActiveRecord::Migration
  def self.up
    create_table :products do |t|
      t.string :title
      t.text :description
      t.string :image_url
      t.decimal :price, :precision => 8, :scale => 2
开发者_运维百科
      t.timestamps
    end
  end

  def self.down
    drop_table :products
  end

end

one of the lines makes me most confused is :

t.string :title

I just can't understand it. So could any of you give me some hint on which part of ruby grammar I need to read in order to understand this single line of code? thanks in advance.


This is just normal Ruby messaging syntax.

t.string :title

means

  1. dereference the block local variable t
  2. send the message :string to the object referenced by t and pass the literal symbol :title as the only argument


I'm guessing a bit here, but as a basis for exploration

:title is a Ruby "symbol" - basically a hack to provide higher-efficiency string-like constants - so t.string :title is a bit like calling a t.string("title") in more popular OO languages, and given you seem to be declaring a record structure for the database, I'd say that's adding a field effectively "called" title with type "string".


You will find the answer within Why's poignant guide to Ruby

P.S. It's spelt grammar, but for code we'd usually use the word 'syntax'. :)


Check this out this might prove to be very helpful This file is called migration file it creates the backend for your app Another link


to fully understand that file, you need to understand classes, inheritance, modules, method calling, blocks and symbols.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜