Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top