Foreign Keys Put in DB Automatically, no?

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


John K.
[email protected]

http://www.kopanas.com
http://www.cusec.net
http://www.soen.info

On 9/19/06, John K. [email protected] wrote:

That makes no sense. I though all this time the foreign key was
automatically stored. Am I going crazy?

@picture = @user.pictures.build(params[:picture])

.new does look awfully nice there, however.

jeremy

On 9/19/06, John K. [email protected] wrote:

And now I hace the following code:

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

(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.)

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?

On 9/19/06, Jeremy K. [email protected] wrote:

jeremy


John K.
[email protected]

http://www.kopanas.com
http://www.cusec.net
http://www.soen.info

You are right!

But it does say here that build is protected:
http://api.rubyonrails.com/classes/ActiveRecord/Associations/ClassMethods/JoinDependency.html#M000539

On 9/19/06, Jeremy K. [email protected] wrote:

protected and new should be used instead?

jeremy


John K.
[email protected]

http://www.kopanas.com
http://www.cusec.net
http://www.soen.info

On 9/19/06, John K. [email protected] wrote:

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?

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

jeremy

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs