7

私は次のクラスを持っています:

  • 計画
  • >開発者
  • >マネージャー

Projectモデルに次のステートメントを追加しました。

has_and_belongs_to_many :people
accepts_nested_attributes_for :people

そしてもちろん、クラス内の適切なステートメントPerson。メソッドを介してをに追加するDeveloperにはどうすればよいですか?以下は機能しません。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

Rails3のソリューション:現在のクラスメソッドのattributes_protected_by_default :

class Person < ActiveRecord::Base

  private

  def self.attributes_protected_by_default
    super - [inheritance_column]
  end
end
于 2012-07-04T09:00:29.863 に答える
5

数日前に同様の問題が発生しました。STIモデルの継承列(つまりtype)は保護された属性です。クラスのデフォルトの保護を上書きするには、次の手順を実行しますPerson

レール2.3

class Person < ActiveRecord::Base

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

Rails 3

@toklandによって提案された解決策を参照してください。

警告:

システム保護属性をオーバーライドしています。

参照:

トピックに関する質問

于 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 に答える