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|
到底是什么意思? 求高人解答
伊谢尔伦2017-04-21 11:18:31
create_table :books do |t|
Not an iteration but a callback.
About callbacks in Ruby:
http://stackoverflow.com/questions/1677861/how-to-implement-a-callback-in-ruby
About Rails Migration:
http://guides.rubyonrails.org/migrations.html
If you have done Ajax with jQuery, you should have an experience similar to this:
$.get("test.php", function(data){ alert("Data Loaded: " + data);
The return value of the $.get()
method is the response body of test.php. The first parameter is the requested URL, and the second parameter is the callback function. This function accepts the response body of test.php as the value of the parameter data, and passes the pop-up window show.
You can understand this Migration statement this way.
# 创建了一个名为books的表
create_table :books do |t| # t是create_table方法的返回值
t.column :title, :string, :limit => 32, :null => false # 创建一个列title,字符串,最大长度32,不为null
t.column :price, :float # 创建一个列price,浮点型
t.column :subject_id, :integer # 创建一个列subject_id,整形
t.column :description, :text # 创建一个列description,文本
t.column :created_at, :timestamp # 创建一个列created_at,时间戳
end
ringa_lee2017-04-21 11:18:31
Here: /q/1010000000266437 I’ve already gone back and moved it here again.
create_table :books do |t|
do|x|...end has no special meaning, just like {|x|}, it just represents a block. There is iteration in this code, it is actually similar to:
File.open("xxx","xxx") do |f|
f.write(...)
end
Yes, of course this is also legal:
File.open("xxx","xxx") { |f|
f.write(...)
}
Then it becomes like the above because the brackets can be omitted.
For ruby to implement such a function, you only need:
class Somethings
#...
def create_table(name)
# 为创建这个表做一些准备……
# ...
yield @table
# 创建这个表
# ...
end
end
For more specific usage of iterators, you can read this: http://blog.csdn.net/classwang/article/details/4692856
大家讲道理2017-04-21 11:18:31
do ... end is equivalent to { ... }, which is a block. Ruby methods can accept block parameters