【问题标题】:Nested attributes not saved嵌套属性未保存
【发布时间】:2013-11-19 20:23:35
【问题描述】:

我有一个可以有很多付款的用户类。 用户会得到保存,但付款不会。

class User < ActiveRecord::Base
  attr_accessible :email, :password, :password_confirmation
  attr_accessor :payments, :payments_attributes
  attr_accessible :payments_attributes, :payments
  has_many :payments, :inverse_of => :user, :autosave => true
  accepts_nested_attributes_for :payments, allow_destroy: false
end

class Payment < ActiveRecord::Base
  # it looks that I do not need the attr_accessor methods
  #attr_accessor :method, :paid, :amount, :creditcard, :security_code, :expires_at

  attr_accessible :method, :paid, :amount, :creditcard, :security_code, :expires_at
  attr_accessible :created_at, :user_id

  belongs_to :user, :inverse_of => :payments

  validates_presence_of :method
end

我已经尝试过这种方法:

User.create!( { email: "asdf@asdf.com", payments: {paid: false, method: "bank"} } )

有没有不通过的解决方法:

u = User.new(params)
u.payments(payments_params)
u.save!

【问题讨论】:

    标签: ruby-on-rails nested-attributes fabrication-gem


    【解决方案1】:

    这样做应该可以:

    User.create!( { 
      "email" =>  "asdf@asdf.com", 
      "payments_attributes" => [{paid: false, method: "bank"}] 
    } )
    

    【讨论】:

    • 然后我得到:ActiveModel::MassAssignmentSecurity::Error: Can't mass-assign protected attributes: payments[] 我使用 attr_accessor :payments, :payments_attributes attr_accessible :payments_attributes, :payments
    • 糟糕,忘记了_attributes 部分。 payments_attributes[] 应该适合你。
    • 同样的问题:ActiveModel::MassAssignmentSecurity::Error: Can't mass-assign protected attributes: payments_attributes[]
    • 如果删除payments_attributes 末尾的[] 会怎样?
    • 回滚,抱歉,付款未保存
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多