以下是我的参数,
{
:project_id => "1",
:ticket => {:name => "Ticket1"}
}
如何将project_id添加到允许的参数中?
控制器
params.require(:ticket)permit(:name)
以下是我所做的
我为项目参数添加了另一个功能
def ticket_group_params
params.require(:ticket_group).permit(:name)
end
def project_params
params.permit(:project_id)
end
然后我只是合并结果,只为创建操作,例如
# POST /ticket_group
# POST /ticket_group.json
def create
@ticket_group = TicketGroup.new(ticket_group_params.merge(project_params))
respond_to do |format|
def ticket_params
name_params = params.require(:ticket).permit(:name)
name_params.merge(params.permit(:project_id))
end
# => {name: 'val', project_id: 'val'}
或
def ticket_params
params.require(:ticket).permit(:name).tap do |_params|
_params[:project_id] = params.permit(:project_id)
end
end
# => {name: 'val', project_id: 'val'}
或者,它可能是
def ticket_params
params.permit(:project_id, ticket: [:name])
end
# => {project_id: 'val', ticket: {name: 'val'}}
您可能需要将其作为隐藏属性添加到表单中,如下所示:
<input type="hidden" name="ticket[project_id]" value="<%= @ticket.project_id %>" />
然后在控制器中你可以这样做:
params.require(:ticket).permit(:name,:project_id)
这里有一个有用的链接:https://github.com/rails/strong_parameters