【发布时间】:2013-12-04 21:59:02
【问题描述】:
我有一个拥有_many 服务的用户:
class User < ActiveRecord::Base
has_many :services
accepts_nested_attributes_for :services, :reject_if => lambda { |s| s[:name].blank? }, :allow_destroy => true
end
这是我的控制器操作(设计)
def new
build_resource({})
5.times { resource.services.build }
...
end
def create
build_resource(sign_up_params)
resource.services.build(sign_up_params[:services_attributes])
...
end
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) do |u|
u.permit(:email, :password, :password_confirmation,
services_attributes: [:name])
end
end
当我提交表单时,这里是相关的参数哈希:
{...,
"services_attributes"=>{
"0"=>{"name"=>"Test"},
"1"=>{"name"=>""},
"2"=>{"name"=>""},
"3"=>{"name"=>""},
...}
给我以下错误:
unknown attribute: 0
在那种情况下,我不知道如何使用强参数保存多个对象。我的想法是做这样的事情:
在我的创建方法中:
resource.services.build(sign_up_params[:services_attributes][:id])
它可以保存对象,但我对此感到不舒服...感谢您的解释!
【问题讨论】:
标签: ruby-on-rails-4 nested-attributes strong-parameters