Push question

In my app, a Post belongs_to a user and a User has_many posts.

Say I’d like to change the user the post belongs to.

post = Post.find(1)
post.user << anotheruser

… gives me an error, since post.user is already defined. It also seems
as if changing the attribute user_id in this manner:

post.update_attributes(:user_id => 1)

doesn’t help either.

What’s the best way to do this?

PLease provide more code to get help. Thanks. I don’t understand why do
you need add a another user to post. If you want this, then the
association is has_and_belongs_to_many or has_many :through between the
model users and posts.

Nicolas Santa wrote:

PLease provide more code to get help. Thanks. I don’t understand why do
you need add a another user to post. If you want this, then the
association is has_and_belongs_to_many or has_many :through between the
model users and posts.

Sorry, what I mean is that I’d like to change which user the post
belongs to, not add other ones. Here’s more code:

class User < ActiveRecord::Base
has_many :posts
end

class Post < ActiveRecord::Base
belongs_to :user
end

in the db schema:

create_table “posts”, :force => true do |t|
t.column “user_id”, :integer
end

Thanks in advance for any help.

Read the documentation for belongs_to at api.rubyonrails.com

Hint: you’re not pushing a value onto a collection, you are setting a
value on at attribute.

ReinH

On Sep 7, 5:03 am, “Mariko C.” [email protected]