Foreign key confusion

I have 2 models right now: “users” and “posts”. When a user creates a
post I would like their id to be recorded under “user_id” in the “posts”
table. Under the “user” model I have:

class User < ActiveRecord::Base
has_many :posts
end

And under the “posts” model I have:

class Post < ActiveRecord::Base
belongs_to :user
end

When I create a post everything goes fine, but the “user_id” field in
“posts” is left at 0. I know I’m missing something, but I can’t seem to
translate all the documentation out there into my scenario. Any help
would be MUCH appreciated.

Jasbur wrote:

class Post < ActiveRecord::Base
belongs_to :user
end

When I create a post everything goes fine, but the “user_id” field in
“posts” is left at 0. I know I’m missing something, but I can’t seem to
translate all the documentation out there into my scenario. Any help
would be MUCH appreciated.

hm, how are you taking what’s in @session[:user].id and putting it in
your post ?
in the controller, when you’re creating the post, you could do :

@post = Post.new(@params[:post_formstuff])
@post.user_id = @session[:user].id
@post.save

Also, something that may be wrong too, i tend to explicitly mention the
foreign_key in the model.

belongs_to :user, :foreign_key => “user_id”

that may work, however its early for me and i need coffee.

d.

Well, even without your coffee you scooled me :slight_smile: I did have to change:

@post.user_id = @session[:user].id

to

@post.user_id = @session[‘user’].id

for some reason. But it works great. I was looking at the active record
stuff as more of a “write” function than a “read” function. I thought it
would figure the syntax of the session itself.

Thanks again

you’re not confused
well, it kinda depends on how you created your post
what your doing is correct, look

use script/console

require ‘pp’ #=> just for pretty printing

rodney = User.create(:name => ‘rodney’)

pp rodney
#<User:0x332dcfc
@attributes={“name”=>“rodney”, “id”=>1},

[snip]

post = Post.create(:title => ‘The World is all that is the case’,
:body => ‘Too Wittgy’, :user => rodney )

pp post

pp post
#<Post:0x32187e0
@attributes=
{“body”=>“Too wittgy”,
“title”=>“The World is all that is the case”,
“id”=>1,
“user_id”=>1},
[ snip ]

your post has user_id set to 1

hth

/r/r

On 6/8/06, Jasbur [email protected] wrote:

class Post < ActiveRecord::Base


Rails mailing list
[email protected]
http://lists.rubyonrails.org/mailman/listinfo/rails


Rodney
http://www.pinupgeek.com
http://www.dutchrailers.org