class Books < ActiveRecord::Migration
def self.up
create_table :books do |t|
t.column :title, :string, :limit => 32, :null => false
t.column :price, :float
t.column :subject_id, :integer
t.column :description, :text
t.column :created_at, :timestamp
end
end
def self.down
drop_table :books
end
end
create_table :books do |t|
這一句 沒有迭代操作 為什麼會有 ruby do |t|
這句呢 這裏的 ruby do |t|
到底是什麼意思? 求高人解答
認(rèn)證高級PHP講師
create_table :books do |t|
不是迭代而是回調(diào)。
關(guān)於Ruby的回呼:
http://stackoverflow.com/questions/1677861/how-to-implement-a-callback-in-ruby
關(guān)於Rails的Migration:
http://guides.rubyonrails.org/migrations.html
如果你用jQuery做過Ajax的話,應(yīng)該有類似這樣的經(jīng)驗:
$.get("test.php", function(data){ alert("Data Loaded: " + data);
$.get()
方法的回傳值是test.php的response body,第一個參數(shù)是請求的url,第二個參數(shù)就是回調(diào)函數(shù),這個函數(shù)接受test.php的response body作為參數(shù)data的值,並且透過彈窗顯示。
這條Migration語句你可以這麼理解。
# 創(chuàng)建了一個名為books的表
create_table :books do |t| # t是create_table方法的返回值
t.column :title, :string, :limit => 32, :null => false # 創(chuàng)建一個列title,字符串,最大長度32,不為null
t.column :price, :float # 創(chuàng)建一個列price,浮點型
t.column :subject_id, :integer # 創(chuàng)建一個列subject_id,整形
t.column :description, :text # 創(chuàng)建一個列description,文本
t.column :created_at, :timestamp # 創(chuàng)建一個列created_at,時間戳
end
在這裡:/q/1010000000266437 已經(jīng)回過一遍了,再搬過來。
create_table :books do |t|
do|x|...end沒有什麼特殊的意義和{|x|}一樣,只是代表一個block而已, 這個程式碼中是有迭代出現(xiàn)的,他其實是類似:
File.open("xxx","xxx") do |f|
f.write(...)
end
的,當(dāng)然這樣也是合法的:
File.open("xxx","xxx") { |f|
f.write(...)
}
然後因為括號可以省略就變成上面的樣子了。
對於ruby來說要實現(xiàn)這樣的功能,只需要:
class Somethings
#...
def create_table(name)
# 為創(chuàng)建這個表做一些準(zhǔn)備……
# ...
yield @table
# 創(chuàng)建這個表
# ...
end
end
關(guān)於迭代器更具體的用法可以看看這個:http://blog.csdn.net/classwang/article/details/4692856