嵌套属性可以与inheritance结合使用吗?
我有以下课程:
- 项目
- 人
- 人 > 开发人员
- 人 > 经理
在Project
模型中,我添加了以下语句:
has_and_belongs_to_many :people accepts_nested_attributes_for :people
当然还有Person
类中的相应语句。 如何通过nested_attributes
方法将Developer
添加到Project
? 以下不起作用:
@p.people_attributes = [{:name => "Epic Beard Man", :type => "Developer"}] @p.people => [#]
如您所见, type
属性设置为nil
而不是"Developer"
。
我前几天遇到过类似的问题。 STI模型中的inheritance列(即type
)是受保护的属性。 执行以下操作以覆盖Person
类中的默认保护。
Rails 2.3
class Person < ActiveRecord::Base private def attributes_protected_by_default super - [self.class.inheritance_column] end end
Rails 3
请参阅@tokland建议的解决方案 。
警告:
您正在覆盖系统保护的属性。
参考:
关于这个主题的问题
Rails3的解决方案 : attributes_protected_by_default现在是一个类方法:
class Person < ActiveRecord::Base private def self.attributes_protected_by_default super - [inheritance_column] end end
上面的补丁对我不起作用,但是这样做了(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
对于我们这些使用Mongoid的人,您需要使_type
字段可访问:
class Person include Mongoid::Document attr_accessible :_type end