Вложените атрибути не са запазени

Имам потребителски клас, който може да има много плащания. Потребителят ще бъде спасен, но плащанията не.

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: "[email protected]", payments: {paid: false, method: "bank"} } )

Има ли решение да направите това без преминаване:

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

person Jan    schedule 19.11.2013    source източник


Отговори (1)


Правейки го по този начин, трябва да работи:

User.create!( { 
  "email" =>  "[email protected]", 
  "payments_attributes" => [{paid: false, method: "bank"}] 
} )
person Maurício Linhares    schedule 19.11.2013
comment
Тогава получавам: ActiveModel::MassAssignmentSecurity::Error: Can't mass-assign protected attributes: payments[] И използвам attr_accessor :payments, :payments_attributes attr_accessible :payments_attributes, :payments - person Jan; 20.11.2013
comment
Опа, забравих _attributes парчето. payments_attributes[] трябва да работи за вас. - person Maurício Linhares; 20.11.2013
comment
Същият проблем: ActiveModel::MassAssignmentSecurity::Error: Can't mass-assign protected attributes: payments_attributes[] - person Jan; 20.11.2013
comment
Какво се случва, ако премахнете [] в края на payments_attributes? - person Maurício Linhares; 20.11.2013
comment
Връщане назад, съжалявам, плащанията не се запазват - person Jan; 20.11.2013
comment
Това е странно. Ако беше грешка при валидиране, поне щеше да предизвика изключение. - person Maurício Linhares; 20.11.2013