【问题标题】:has_many Nested Attributes in Rails 4 (save multiple objects with strong parameters)Rails 4 中的 has_many 嵌套属性(使用强参数保存多个对象)
【发布时间】: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


    【解决方案1】:

    应该只有:

    def create
      build_resource(sign_up_params)
      ...
    end
    

    【讨论】:

    • 您的解决方案仅适用于设计?我遇到了同样的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-12
    相关资源
    最近更新 更多