0

I have 2 ActiveRecord objects:

Location

  • id
  • name
  • clip_id

Clip

  • id
  • name

(in the interest of brevity - I have only listed properties relevant to this question)

and currently clip belongs_to location - and this works as expected.

However, my project now necessitates that Location needs to own 2 clips. One that I would like to name listing_clip and one that I would like to name description_clip. How can I do this?

4

3 回答 3

3

在数据库中对此建模的最“正确”方法是在您的locations表中有一对外键,指向该clips表。为此,您可以反转关联,并将 alisting_clip_id和 a添加description_clip_idlocation表中。

然后,修改您的关联:

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

listing_clip如果 of和之间的属性description_clip相同(除了该名称)并且您没有预见到未来的差异,您可以使用剪辑上的新列保持它干燥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 回答