views:

138

answers:

3

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 an 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.

+1  A: 

Change your column name from type to other. type is reserved for the mysql.

Salil
Type must be there for STI to work. I could make a new attribute person_type and copy it's content before saving into the type attribute with a callback. But there surely is a more elegant solution.
Ermin
In one case it save nil if you give datatype of column INTEGER and saving the string.check datatype for column type.
Salil
t.string :typeGood idea though.
Ermin
+1  A: 

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

class Person < ActiveRecord::Base

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

Caveat:

You are overriding the system protected attribute.

Reference:

SO Question on the topic

KandadaBoggu
A: 

Patches above did not work for me, but this did (Rails3):

class ActiveRecord::Reflection::AssociationReflection
  def build_association(*options)
    if options.first.is_a?(Hash) and options.first[:type].presence
      options.first[:type].to_s.constantize.new(*options)
    else
      klass.new(*options)
    end
  end
end

Foo.bars.build(:type=>'Baz').class == Baz

grosser