1

関連テーブルと単一テーブルの継承(「STI」)をいじろうとしています。男性、女性、関係モデルがあります。Relationship モデルには type 列があるため、STI を使用できます。また、Friend は関係の 1 つのタイプになるため、Relationship を継承する Friend モデルも作成しました。

Man.rb

   attr_accessible :name
   has_many :relationships
   has_many :women, :through => :relationships

女性.rb

attr_accessible :name
has_many :relationships
has_many :men,  :through => :relationships

ミートアップ モデルでは、日付がいつどこで行われたかを追跡したいと考えています。

関係.rb

   attr_accessible :type
   belongs_to :woman
   belongs_to :man

フレンド.rb

class Friend < Relationship

end

しかし、friend 型との関係を作成しようとすると、サブクラスが存在しないという警告メッセージが表示されます。コンソールで、私はこれをやっています

     sarah = Woman.create!(name: 'Sarah')
     jim = Man.create!(name: 'Jim')

     jim.relationships.build(type: 'Friend', woman_id: 1)
=> #<Relationship id: nil, type: "Friend", man_id: 1, woman_id: 1, created_at: nil, updated_at: nil>

     jim.save!

しかし、ジムの関係を取得しようとすると、

>> jim.relationships
  Relationship Load (0.3ms)  SELECT "relationships".* FROM "relationships" WHERE "relationships"."man_id" = 1
ActiveRecord::SubclassNotFound: The single-table inheritance mechanism failed to locate the subclass: 'friends'. This error is raised because the column 'type' is reserved for storing the class in case of inheritance. Please rename this column if you didn't intend it to be used for storing the inheritance class or overwrite Relationship.inheritance_column to use another column for that information.

「友達」ではなく「友達」との関係を作ろうとしても同じです。

 jim.relationships.build(type: 'friends', woman_id: 1)

私が間違っていることを説明できますか?

友達のためにデータベースにテーブルを作成しませんでした。リレーションシップ モデルにすべてを格納できると思いました。これは単なる遊びのアプリなので、Relationship モデルの type 属性のみを割り当てました。

4

1 に答える 1

0

タイプの値は小文字で単数形にする必要があると思います - friend?

しかし実際には、おそらくオブジェクトを使用して、レールにそれを処理させたいと思うでしょう。

sarah = Woman.create!(name: 'Sarah')
jim = Man.create!(name: 'Jim')
Friend.create!(women: sarah, man: jim)

男性の女性モデルは私には意味がありません - 彼らは両方とも人であり、関係は性別に関係なく2人だけであるべきです.

于 2013-03-15T23:48:44.760 に答える