在创建对象之前需要对 Rails 5 和参数进行permit
测试,这是将参数合并current_user
到参数中的最简单方法,感谢@Peter Brown 在他的回答中:
def create
@discussion = current_user.materials.new(new_material_params)
# ...
end
private
def new_material_params
params.require(:material).permit(:title, :description,: content)
end
如果您使用嵌套对象创建accepts_nested_attributes_for
,则需要手动深度合并到关联参数中:
class User < ApplicationRecord
has_many :discussions # Used to associate User with Discussion later
end
class Comment < ApplicationRecord
belongs_to :user
end
class Discussion < ApplicationRecord
belongs_to :user
has_many :comments
accepts_nested_attributes_for :comments
end
class DiscussionsController < ApplicationController
def create
# Merge the params[:discussion][:user_id] by using the relationship's #new
@discussion = current_user.discussion.new(new_discussion_params)
end
private
# Sanitized params for creation, not editing
def new_discussion_params
params.require(:discussion)
.permit(:title, :user_id,
comments_attributes: [:id, :content, :discussion_id, :user_id])
.tap do |discussion_params|
# Require the association parameters, and if they exist,
# set :user_id for each.
discussion_params.require(:comments_attributes).each do |i, comment|
comment.merge!(user_id: current_user.id)
end
end
end
end
注意:设置(或覆盖!)哪些内容params[:discussion][:comments_attributes]["0"][:user_id]
适合创建。但是,如果您允许编辑除创建之外的深层层次结构,请确保您不会意外覆盖:user_id
当前用户的所有 s。