嵌套形式产生在父子之间具有额外级别的参数

Nested form yields parameters with extra level between parent and child

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

"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

应为零。如果您有多个 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

希望对您有所帮助。