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
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
.
You can create a score by using the below example
@match.build_score
or
@match.create_score
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