Ruby语法问题

时间:2010-11-24 09:55:20

标签: ruby activerecord

我是红宝石的新手。所以我对以下几行代码感到困惑:

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

其中一条线让我最困惑的是:

t.string :title

我无法理解。那么你们中的任何人都可以给我一些暗示,我需要阅读哪一部分ruby语法才能理解这一行代码?提前谢谢。

5 个答案:

答案 0 :(得分:3)

这只是普通的Ruby消息传递语法。

t.string :title

表示

  1. 取消引用块本地变量t
  2. 将消息:string发送到t引用的对象,并将文字符号:title作为唯一参数传递

答案 1 :(得分:1)

我在这里猜测一下,但作为探索的基础

:title是一个Ruby“符号” - 基本上是提供更高效率的类字符串常量的hack - 所以t.string:title有点像在更流行的OO语言中调用t.string("title"),并给出你似乎在为数据库声明一个记录结构,我会说这是一个有效“称为”标题的字段,其类型为“string”。

答案 2 :(得分:0)

您将在Why's poignant guide to Ruby

中找到答案

P.S。它是拼写语法,但对于代码,我们通常使用“语法”一词。 :)

答案 3 :(得分:0)

检查this out this might prove to be very helpful 此文件名为migration file,它会为您的应用创建后端 Another link

答案 4 :(得分:0)

要完全理解该文件,您需要了解类,继承,模块,方法调用,块和符号。