Foreign Keys Put in DB Automatically, no?

I have the following relationships:

class User < ActiveRecord::Base
  has_many :pictures

class Picture < ActiveRecord::Base
  belongs_to :user

And now I hace the following code:

    @user = User.find params[:id]
    @picture = params[:picture]

But for user_id to be saved in my pictures db I have to add this line of code:

    @picture.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,


@picture =[:picture])

.new does look awfully nice there, however.


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])
@user << @picture

And/or what Jeremy posted. (I find that over-golfing the solution a
bit hard to read, but that's me.)

See the has_many docs. Where are you seeing the docs saying build is protected and new should be used instead?


You are right!

But it does say here that build is protected: