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开发者_StackOverflow中文版 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.
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
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
精彩评论