2

我正在尝试在 has_many 和 belongs_to 关系中创建一个记录

用户有很多帖子和帖子属于用户

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

但我不断收到错误数量的参数错误。

我可以以某种方式自动设置 Post 模型的 user_id 字段吗?我正在使用设计,这是 current_user 调用的来源。

4

3 回答 3

7

还有几种方法:

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

或者:

@post = current_user.posts.build(params[:post])
@post.save
于 2010-12-23T09:00:42.050 回答
3

params[:post]哈希与{:user_id => current_user.id}

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

Hash#merge

于 2010-12-23T08:58:00.543 回答
-2

如果您使用简单的 has_many 和 belongs_to 关联,则 users 表中不需要 post_id 列。帖子表中只需要一个 user_id 列

有了它,你可以这样做:

@post = Post.new(params[:post])
@post.user_id = session[:user_id] #or an equivalent.
@post.save
@user.posts << @post
于 2010-12-23T09:02:29.687 回答