我正在尝试创建一个具有 has_many 和 belongs_to 关系的记录
用户有很多帖子和属于用户的帖子
@post = Post.new( params[:post], :user_id => current_user.id )
@post.save
但我一直收到错误数量的参数错误。
我能以某种方式自动设置 Post 模型的 user_id 字段吗?我正在使用 Devise,这是 current_user 调用的来源。
最佳答案
还有几个方法:
@post = Post.new(params[:post])
@post.user_id = current_user.id
@post.save
或者:
@post = current_user.posts.build(params[:post])
@post.save
关于ruby-on-rails - rails - 如何设置模型新记录的 id 值有很多/属于关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4517033/