hzamani / acts_as_relation

Multi table Inheritance for rails
http://hzamani.github.com/acts_as_relation/
MIT License
180 stars 58 forks source link

Mass Assignment Error of Child Attributes #31

Closed nrodriguez closed 10 years ago

nrodriguez commented 11 years ago

I am trying to call update_attributes on a child object but everytime I call it, it throws a mass assignment issue. I have the attr accessible set for the attribute on the child model but it only seems to work if i set it on the parent.

Here is my parent model:

class PaymentMethod < ActiveRecord::Base
  attr_accessible :user_id, :is_default

  acts_as_superclass

  belongs_to :user
end

My child model:

class CreditCard < ActiveRecord::Base
  attr_accessible :brand, 
    :name, :token, :as_payment_method_id
  acts_as :payment_method
end

And my db schemas:

create_table :payment_methods, :as_relation_superclass => true do |t|
  t.boolean :is_default
  t.integer :user_id

  t.timestamps
end

create_table :credit_cards do |t|
  t.string :name
  t.string :brand
  t.string :token

  t.timestamps
end

There exact error I get is:

$> CreditCard.first.update_attributes(:brand => "123")

CreditCard Load (1.0ms) SELECT "credit_cards".* FROM "credit_cards" INNER JOIN "payment_methods" ON "payment_methods"."as_payment_method_id" = "credit_cards"."id" AND "payment_methods"."as_payment_method_type" = 'CreditCard' LIMIT 1 PaymentMethod Load (0.5ms) SELECT "payment_methods".* FROM "payment_methods" WHERE "payment_methods"."as_payment_method_id" = 3 AND "payment_methods"."as_payment_method_type" = 'CreditCard' LIMIT 1 (0.2ms) BEGIN (0.3ms) ROLLBACK ActiveModel::MassAssignmentSecurity::Error: Can't mass-assign protected attributes: brand from /Users/nephtalirodriguez/.rvm/gems/ruby-1.9.3-p125@tutonic/gems/activemodel-3.2.13/lib/active_model/mass_assignment_security/sanitizer.rb:48:in `process_removed_attributes'

So the issue lies in the child(CreditCard) returning payment method instead of CreditCard. If I was to remove the acts_as :payment_method, it updates fine but then as expected, doesn't have the attributes of it's parent. Any idea what I could do to fix this?

hzamani commented 11 years ago

use attr_accessibles after acts_as in child model:

class CreditCard < ActiveRecord::Base
  acts_as :payment_method
  attr_accessible :brand, :name, :token, :as_payment_method_id
end
igraves commented 11 years ago

Don't mean to bring that back up, but the solution mentioned by hzamani does work for me. Wanted to confirm it in this thread as a proper workaround.