Can nested attributes be used in combination with inheritance?

前端 未结 4 1552
萌比男神i
萌比男神i 2021-01-12 10:24

I have the following classes:

  • Project
  • Person
  • Person > Developer
  • Person > Ma
相关标签:
4条回答
  • 2021-01-12 11:04

    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

    0 讨论(0)
  • 2021-01-12 11:07

    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

    0 讨论(0)
  • 2021-01-12 11:17

    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
    
    0 讨论(0)
  • 2021-01-12 11:22

    For those of us using Mongoid, you will need to make the _type field accessible:

    class Person
      include Mongoid::Document
      attr_accessible :_type
    end
    
    0 讨论(0)
提交回复
热议问题