Reputation: 4975
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
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
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
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