2
class Photo < ActiveRecord::Base 
    has_many :boosts, class_name: BoostedPhoto 
    ... 
end 

class BoostedPhoto < ActiveRecord::Base 
    belongs_to :photo 
end 

这是我有它成立至今,但是当我尝试这样做在控制台:钢轨关系一对多;不能建立子对象?

photo = Photo.first 
photo.boosts.create(title: 'testing') 

我得到下面的结果

(0.3ms) begin transaction 
(0.1ms) rollback transaction 
ActiveRecord::UnknownAttributeError: unknown attribute: photo_id 

被仰视如何做几个小时的关系,我想我可能会忽略一些非常简单的事情......对于新问题感到抱歉,但是我开始把我的头发从挫败中解脱出来!

+0

你有一个名为photo_id'列'的' BoostedPhoto'?该列由轨道用来保存关联。 – klump 2012-03-25 12:11:04

回答

2

boosted_photos表中应该有一个外键列。一般规则是我们把belongs_to的关联,有外键的表的模式,在这里它是BoostedPhoto

后,继应该工作,

photo = Photo.first 
photo.boosts.create(title: 'testing') 
+0

对我很好。看起来photo.boosts.build(标题:'testing')也可以。谢谢。 – Daniel 2014-10-10 22:43:40