ChrisWesAllen
ChrisWesAllen

Reputation: 4975

rails - How do I set the id value of new record of model in has many/belongs to relationship?

I'm trying to create a record that in in a has_many and belongs_to relationship

user hasmany posts and posts belongto user

@post = Post.new( params[:post], :user_id => current_user.id )
@post.save

but I'm keep getting a wrong number of arguments error.

Can i set the user_id field of the Post model automatically somehow? I'm using Devise which is where the current_user call comes from.

Upvotes: 2

Views: 2891

Answers (3)

Aditya Manohar
Aditya Manohar

Reputation: 2274

If you're using simple has_many and belongs_to associations there needn't be a post_id column in the users table. There need only be a user_id column in the posts table

With that you can do :

@post = Post.new(params[:post])
@post.user_id = session[:user_id] #or an equivalent.
@post.save
@user.posts << @post

Upvotes: -2

Jimmy
Jimmy

Reputation: 37081

A couple more ways:

@post = Post.new(params[:post])
@post.user_id = current_user.id
@post.save

Or:

@post = current_user.posts.build(params[:post])
@post.save

Upvotes: 7

Jacob Relkin
Jacob Relkin

Reputation: 163238

Merge the params[:post] hash with {:user_id => current_user.id}:

@post = Post.new(params[:post].merge({:user_id => current_user.id}))
@post.save

See Hash#merge

Upvotes: 3

Related Questions