One-to-One: Undefined method build

后端 未结 3 1326
无人共我
无人共我 2020-12-28 18:27

got a problem with one to one relations

I have some Matches and i want to have one score for a match.

my Match.rb

has_one :score, :dependent          


        
3条回答
  •  無奈伤痛
    2020-12-28 18:47

    You should be doing match.build_score. This is because when you call the score method it would attempt to fetch the association, and because it's not defined yet, it will return nil. Then you call build on nil and that's why it blows up.

    has_many association methods return a sort of "proxy" object to the objects returned by calls to them, so this is why things like posts.comments.build works. The methods for belongs_to and has_one associations attempt to fetch the associations straight off, and so you need to do build_association rather than association.build.

提交回复
热议问题