【问题标题】:Devise and ActiveModel::MassAssignmentSecurity::Error设计和 ActiveModel::MassAssignmentSecurity::Error
【发布时间】:2013-11-27 06:24:51
【问题描述】:

我正在通过设计进行注册过程

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

<!-- 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

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

【问题讨论】:

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


    【解决方案1】:

    您正在尝试分配付款而不是付款属性。如果这是由 fields_for 在视图中返回的,很可能是由于您的 User 模型中缺少 accepts_nested_attributes_for :payments 造成的。

    更新:

    您错过了传递给fields_for 的协会名称中的“s”。应该是

    fields_for :payments  do |payment|
    

    【讨论】:

    • 抱歉复制/粘贴错误:我的模型集中有这些:accepts_nested_attributes_for :payments, allow_destroy: false
    • 你能把你的表单代码也加进去吗? fields_for 不符合您的预期,因此可能存在错误。
    • hm 当我将 :payment 更改为付款时:在我的 devise/registrations/new.html.erb 中,f.fields_for 的整个部分都不会被渲染。
    • 因为您没有为给定型号付款。在你的控制器中添加类似@user.payments.build
    • 必须是payments_attributes: {},而不是payment: {}
    猜你喜欢
    • 2012-04-16
    • 1970-01-01
    • 2013-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多