I have the following relationships:
class User < ActiveRecord::Base
has_many :pictures
end
class Picture < ActiveRecord::Base
belongs_to :user
end
And now I hace the following code:
@user = User.find params[:id]
@picture = @user.pictures.new params[:picture]
But for user_id to be saved in my pictures db I have to add this line of code:
@picture.user_id = @user.id # should not need this... why?
That makes no sense. I though all this time the foreign key was
automatically stored. Am I going crazy?
Thanks for your input :-).
Your Friend,
John
bitsweat
(Jeremy Daer)
2
@picture = @user.pictures.build(params[:picture])
.new does look awfully nice there, however.
jeremy
Are you sure... it works and everything so thanks but according to
docs build is protected method and we should use new instead... is
this new?
(Debatable if you need an instance var here, but let's assume you do)
@picture = Picture.new(params[:picture])
@user << @picture
And/or what Jeremy posted. (I find that over-golfing the solution a
bit hard to read, but that's me.)
bitsweat
(Jeremy Daer)
5
See the has_many docs. Where are you seeing the docs saying build is protected and new should be used instead?
jeremy