嵌套属性未保存

时间:2013-11-19 20:23:35

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

我有一个User类,可以有很多付款。 用户将被保存,但付款不会。

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!

1 个答案:

答案 0 :(得分:0)

这样做应该有效:

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