在Rails 3.1的create调用中使用object代替ID



我使用的是Rails 3.1.3和Ruby 1.9.2,当我在数据库中创建种子数据时,我遇到了一个错误。我正在创建一个简单的葡萄酒收集应用程序,我有一个Grape类只有两个简单的实例(name是"红色"或"白色")。我有一个Varietal类,belongs_to Grape类,也只有一个简单的name字段。

当我去创建一些种子数据时,我使用如下代码:

# create some reds
r = Grape.find_or_create_by_name('Red')
Varietal.find_or_create_by_name_and_grape_id('Cabernet Franc', r)
Varietal.find_or_create_by_name_and_grape_id('Cabernet Sauvignon', r)
Varietal.find_or_create_by_name_and_grape_id('Malbec', r)
# create some whites
w = Grape.find_or_create_by_name('White')
Varietal.find_or_create_by_name_and_grape_id('Chardonnay', w)
Varietal.find_or_create_by_name_and_grape_id('Riesling', w)
Varietal.find_or_create_by_name_and_grape_id('Sauvignon Blanc', w)

奇怪的是,当我去查看数据库中的数据时,所有Varietals都与"红色"Grape相关联。使用Rails控制台,我发现如果我从找到的Grape实例而不是实例本身传递id字段,我就会得到正确的行为。

我错过了什么吗?我认为在Rails中,您可以始终传递ActiveRecord对象来代替原始ID,并且它会自动查找id字段值。

通常可以传递对象而不是id,但这往往更多地涉及路由和关联。

您要求它通过namegrape_id查找,但传递了名称和葡萄实例,这就是问题所在。

如果在查找器中规定了id,则需要传入id。

rw应该返回Grape对象,对吗?所以你不能像这样访问他们的id元素吗?

# save grape stuff by entering the ID instead of the object
# create some reds
r = Grape.find_or_create_by_name('Red')
Varietal.find_or_create_by_name_and_grape_id('Cabernet Franc', r.id)
Varietal.find_or_create_by_name_and_grape_id('Cabernet Sauvignon', r.id)
Varietal.find_or_create_by_name_and_grape_id('Malbec', r.id)
# create some whites
w = Grape.find_or_create_by_name('White')
Varietal.find_or_create_by_name_and_grape_id('Chardonnay', w.id)
Varietal.find_or_create_by_name_and_grape_id('Riesling', w.id)
Varietal.find_or_create_by_name_and_grape_id('Sauvignon Blanc', w.id)

这将传入您选择的葡萄的id,并将与您正在使用的动态查找器匹配。

最新更新