Devise和ActiveModel :: MassAssignmentSecurity ::错误

时间:2013-11-14 09:47:27

标签: ruby-on-rails ruby activerecord devise mass-assignment

我正在通过设计

开展注册流程

我尝试将“付款”保存到通过公式注册的“用户”。 当用户从复选框中选择“银行”时,还应为用户创建依赖付款。

<!-- language: ruby -->
class User < ActiveRecord::Base

 devise :database_authenticatable, :registerable, :confirmable,
         :recoverable, :rememberable, :trackable

  attr_accessible :email, :password, :password_confirmation, :remember_me, :first_name, :last_name

  attr_accessible :payments_attributes
  # also tried attr_accessible :payments_attributes, :payments
  has_many :payments, :autosave => true

  accepts_nested_attributes_for :payments, allow_destroy: false

end


class Payment < ActiveRecord::Base

  attr_accessible :method, :paid
  attr_accessor :method, :paid

  belongs_to :user

end

new.html.erb

  <%= f.fields_for :payment do |payment| %>
        <div>
          <%= payment.radio_button(:method, 'bank') %>
          <%= payment.label :bank_transfer %>
          <%= payment.radio_button(:method, 'paypal') %>
          <%= payment.label :paypal %>
        </div>
    <% end %>



These are the attributes I wanna set:

my_attributes = {"first_name"=>"Max", "last_name"=>"Mustermann", "password"=>"12345678", "password_confirmation"=>"12345678", "email"=>"max@mustermann.at", "company"=>"ACME INC", "industry"=>{"title"=>"Metall", "oenace"=>"123"}, "payments"=>{"method"=>"bank_transfer", "paid"=>"false"}}

User.new(my_attributes)
# ActiveModel::MassAssignmentSecurity::Error: Can't mass-assign protected attributes: payments

我还尝试将其添加到用户模型中:

  def after_initialize
    self.payments.build if self.payments.blank?
  end

为什么没有保存这些参数的任何想法或建议?

1 个答案:

答案 0 :(得分:0)

您正在尝试分配付款而不是payment_attributes。如果视图中的fields_for返回了此内容,则很可能是因为用户模型中缺少accepts_nested_attributes_for :payments

更新:

您错过了's',因为您的关联名称已转移到fields_for。应该是

fields_for :payments  do |payment|