我在嵌套属性和Devise方面遇到了问题。 与如何在设计模型中使用嵌套属性类似的问题。据我所知,我已经按照此处的建议设置了所有内容:覆盖设计注册控制器
我已经为用户和订阅设置了关联,我已经"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
设计/注册/新.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
我尝试在attr_accessible
中使用subscription_attributes
(单数),但这不起作用。
对我可能做错了什么有什么建议吗?谢谢。
由于您的用户和订阅模型之间存在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 文档的"嵌套属性示例"部分(一对多)。