One-to-One: Undefined method build

后端 未结 3 1313
无人共我
无人共我 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.

    0 讨论(0)
  • 2020-12-28 19:03

    You can create a score by using the below example

    @match.build_score
    or
    @match.create_score
    
    0 讨论(0)
  • 2020-12-28 19:13

    Use build instead of new:

    def new
        @match = Match.find(params[:match_id])
        @score = @match.build_score
    end
    

    Here are the docs for this: http://guides.rubyonrails.org/association_basics.html#belongs_to-build_association

    Similarly, in the create method, do it like this:

    def create
        @match = Match.find(params[:match_id])
        @score = @match.create_score(params[:score])
    end
    

    Docs for this: http://guides.rubyonrails.org/association_basics.html#belongs_to-create_association

    0 讨论(0)
提交回复
热议问题