Fixing Rails nested attributes on collections with sti

user.persons.build(:type=>’Manager’).class != Manager, which makes a lot of problems with single table inheritance, especially when dealing with accepts_nested_attributes_for / fields_for that rely on correct class of the associated.

# Make build associations have their given type
# Makes that: user.persons.build(:type=>Manager).class == Manger
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

rails issue

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s