使用带有Devise的嵌套属性时的批量赋值警告

时间:2011-05-14 22:07:59

标签: ruby-on-rails ruby-on-rails-3 devise nested-attributes

我遇到嵌套属性和设计问题。与How do I use nested attributes with the devise model类似的问题。 据我所知,我已按照此处的建议设置了所有内容: Override devise registrations controller

我已经设置了用户和订阅的关联,我有"accepts_nested_attributes_for",并在:subscriptions_attributes中包含了attr_accessible,但我收到了Devise控制器的警告。

class User < ActiveRecord::Base
    devise :database_authenticatable, :registerable,:recoverable, :rememberable, :trackable, :validatable
    validates_presence_of :first_name, :last_name
    has_many :subscriptions
    accepts_nested_attributes_for :subscriptions
    attr_accessible :first_name, :last_name, :email, :password, :password_confirmation, :remember_me, :subscriptions_attributes    
    ... 
end

-

class Subscription < ActiveRecord::Base
  belongs_to :user
  validates_presence_of :user_id, :chargify_subscription_id, :chargify_product_handle
  attr_accessible :user_id, :chargify_subscription_id, :chargify_product_handle
  ... 
end

设计/注册/ new.html.erb:

<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %>
    <%= devise_error_messages! %>
    <p><%= f.label :first_name %><br />
      <%= f.text_field :first_name %></p>
    ...

    <%= f.fields_for :subscription do |s| %>
        <p><%= s.label :chargify_subscription_id %><br />
          <%= s.text_field :chargify_subscription_id %></p>
            ...

我收到以下警告:

Started POST "/users" for 127.0.0.1 at Sat May 14 12:38:49 -0700 2011
  Processing by Devise::RegistrationsController#create as HTML
  Parameters: {"commit"=>"Sign up", "authenticity_token"=>"wNZhZgIhYm9CpZfhvDiRBqaJseoO8QvR0Mk9VIybhcI=", "utf8"=>"✓", "user"=>{"password_confirmation"=>"[FILTERED]",        "last_name"=>"9", "subscription"=>{"chargify_product_handle"=>"medium", "chargify_subscription_id"=>"123"}, "password"=>"[FILTERED]", "first_name"=>"9", "email"=>"99@99.     com"}}
WARNING: Can't mass-assign protected attributes: subscription

我已尝试在subscription_attributes中使用attr_accessible(单数),但这不起作用。

对于我可能做错的任何建议? 感谢。

1 个答案:

答案 0 :(得分:5)

由于您的用户和订阅模型之间存在has_many关联,因此我认为您需要指定fields_for :subscriptions而不是fields_for :subscription

<%= f.fields_for :subscriptions do |s| %>
    <p><%= s.label :chargify_subscription_id %><br />
      <%= s.text_field :chargify_subscription_id %></p>
        ...

然后,使用subscriptions_attributes参数传递fields_for范围内的属性,该参数应该有效,因为您有attr_accessible :subscriptions_attributes

有关嵌套has_many关联表单的更多示例,请查看Rails documentation的“嵌套属性示例”部分(一对多)。