7

我有以下课程:

  • 项目
  • 人员>开发人员
  • >经理

Project模型中,我添加了以下语句:

has_and_belongs_to_many :people
accepts_nested_attributes_for :people

当然还有课堂上的适当陈述Person。如何通过该方法将 a 添加Developer到 a ?以下不起作用:Projectnested_attributes

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

如您所见,type属性设置为nil而不是"Developer".

4

4 回答 4

7

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
于 2012-07-04T09:00:29.863 回答
5

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

于 2010-03-31T18:58:44.987 回答
4

上面的补丁对我不起作用,但确实如此(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

于 2010-06-03T20:22:28.763 回答
0

对于我们这些使用 Mongoid 的人,您需要使该_type字段可访问:

class Person
  include Mongoid::Document
  attr_accessible :_type
end
于 2013-06-29T03:27:59.913 回答