0

2 つの ActiveRecord オブジェクトがあります。

位置

  • ID
  • 名前
  • clip_id

クリップ

  • ID
  • 名前

(簡潔にするために、この質問に関連するプロパティのみをリストしました)

現在clip belongs_to location、これは期待どおりに機能します。

ただし、私のプロジェクトでは、Location2 を所有する必要がありますclips。名前を付けたいものと名前listing_clipを付けたいものdescription_clip。これどうやってするの?

4

3 に答える 3

3

The most "correct" way to model this in the database is to have a pair of foreign keys in your locations table, pointing to the clips table. To achieve this, you can invert the association, and add a listing_clip_id and a description_clip_id to your location table.

Then, modify your associations:

class Location < ActiveRecord::Base
  belongs_to :listing_clip, class_name: 'Clip'
  belongs_to :description_clip, class_name: 'Clip'
end

class Clip < ActiveRecord::Base
  has_one :listed_location, class_name: 'Location', foreign_key: 'listing_clip_id'
  has_one :described_location, class_name: 'Location', foreign_key: 'description_clip_id'
end
于 2013-10-16T22:09:48.333 に答える
2

clips次のように、呼び出されたテーブルに追加の列を追加して、モデルclip_type内の関連付けを参照できます。Location

class Location < ActiveRecord::Base
  has_one :listing_clip, class_name: 'Clip', conditions: { clip_type: 'listing' }
  has_one :description_clip, class_name: 'Clip', conditions: { clip_type: 'description' }
end

class Clip < ActiveRecord::Base
  belongs_to :location
end
于 2013-10-16T22:03:21.597 に答える
0

If the properties between of listing_clip and description_clip are the same (other than that name) and you don't foresee furture differences you can keep it DRY with a new column on clip called clip_type:

class Location < ActiveRecord::Base
  has_many :clips, limit: 2
end

class Clip < ActiveRecord::Base
  attr_accessor :clip_type
  belongs_to :location
end
于 2013-10-16T22:10:47.247 に答える