嵌套表单生成父级和子级之间额外级别的参数

时间:2015-05-23 00:19:33

标签: ruby-on-rails ruby-on-rails-4 devise

我正在构建一个用户,然后以一种形式构建该用户的计划。我希望参数看起来像这样:

"user"=> {
    "email" => "",
    "plans_attributes", => {
       "invite_code" => "",
       "zipcode => ""
    }
}

但它看起来像这样:

"user"=> {
   "email"=>"", 
   "plans_attributes"=> {
      "0" => {
         "invite_code"=>"", 
         "zipcode"=>""
      }
   }
}

不确定为什么0出现......是正常的?如果没有,我该如何摆脱它?如果是这样,我如何让参数适当地接受?

代码:

class User < ActiveRecord::Base
  has_many :plans #a user definitely can have more than one plan, but at the time of sign_up, they can only create one plan
  accepts_nested_attributes_for :plans
end

class Plan < ActiveRecord::Base
  belongs_to :user
end

    <% resource.plans.build %>
    <%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
        <%= devise_error_messages! %>
        <%= f.hidden_field :email %>

          <!-- Begin nested form for plan -->
          <%= f.fields_for :plans do |p| %>
            <%= p.hidden_field :invite_code %>
            <%= p.hidden_field :zipcode %>
          <%= end %>
    <% end %>

注意,如果0应该在那里,不知道如何使这个工作:

def configure_sign_up_params
  devise_parameter_sanitizer.for(:sign_up) do |u|
    u.permit( 
      :email,
      plans_attributes: [
        0: [
          :invite_code, 
          :zipcode,
        ] 
      ]  
    )
  end
end

#Throws an unexpected ':' after 0 error even if 0 is a string

1 个答案:

答案 0 :(得分:1)

预期为零。如果您有多个plans_attributes,它会显示为: { 0 => {"invite_code"=>"", "zipcode"=>""} 1 => {"invite_code"=>"", "zipcode=>""}}等。

这样,您可以同时更新所有用户的计划。

根据你所写的内容我可以告诉你,你的devise_parameter_sanitizer应如下所示: def configure_sign_up_params devise_parameter_sanitizer.for(:sign_up) do |u| u.permit(:email, plans: [:invite_code, :zipcode]) end end

希望有所帮助。