Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can nested attributes be used in combination with inheritance?

I have the following classes:

  • Project
  • Person
  • Person > Developer
  • Person > Manager

In the Project model I have added the following statements:

has_and_belongs_to_many :people
accepts_nested_attributes_for :people

And of course the appropriate statements in the class Person. How can I add a Developer to a Project through the nested_attributes method? The following does not work:

@p.people_attributes = [{:name => "Epic Beard Man", :type => "Developer"}]
@p.people
=> [#<Person id: nil, name: "Epic Beard Man", type: nil>]

As you can see the type attributes is set to nil instead of "Developer".

like image 476
Hermine D. Avatar asked Mar 31 '10 14:03

Hermine D.


2 Answers

Solution for Rails3: attributes_protected_by_default in now a class-method:

class Person < ActiveRecord::Base

  private

  def self.attributes_protected_by_default
    super - [inheritance_column]
  end
end
like image 92
tokland Avatar answered Sep 30 '22 04:09

tokland


I encountered a similar problem few days ago. The inheritance column(i.e. type) in a STI model is a protected attribute. Do the following to override the default protection in your Person class.

Rails 2.3

class Person < ActiveRecord::Base

private
  def attributes_protected_by_default
    super - [self.class.inheritance_column]
  end
end

Rails 3

Refer to the solution suggested by @tokland.

Caveat:

You are overriding the system protected attribute.

Reference:

SO Question on the topic

like image 30
Harish Shetty Avatar answered Sep 30 '22 02:09

Harish Shetty