2012-01-03 71 views
0

我正在使用Rails 3.1.3和Ruby 1.9.2,并且在我的数据库中创建种子数据时遇到了类似bug的问题。我正在创建一个简单的葡萄酒收集应用程序,并且我有一个Grape类,只有两个简单实例(name是“红色”或“白色”)。我有一个Varietal类,其中belongs_toGrape类,也只有一个简单的name字段。在Rails 3.1中使用对象代替ID创建调用

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

# 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字段值。

+0

我想如果你明确使用动态查找器by_grape_id,那么它期望你通过ID。 – Johny 2012-01-03 23:08:29

+0

如果这是真的,那么为什么带有白色葡萄实例的find_by_grape_id工作得很好?另外,我注意到为find_or_create执行的SQL首先使用白色Grape实例的ID执行正确的SELECT,但是创建Varietal的INSERT具有错误的ID。对我来说似乎仍然是一个错误。 – 2012-01-04 17:51:05

回答

0

您可以正常传递对象而不是ID,但这往往更多地在路由和关联上。

你问它由grape_id找到,但传递一个名字和葡萄实例,这是问题所在。

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

0

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,并将与您正在使用的动态取景器相匹配。