三种模型的非典型关联

时间:2012-08-22 11:00:02

标签: ruby-on-rails activerecord model associations

我正在写一个关于钓鱼的应用程序。

  • 我们有一个包含某些物种的fish模型。
  • 我们有一个包含钓点的location模型。
  • 我们有technique模型,其中包含一些钓鱼技巧。

每个location可能有多个fish,因此:

class Location < ActiveRecord::Base
    has_many :fish
end

每个fish都可以在多个位置找到,所以:

class Fish < ActiveRecord::Base
    has_many :locations
end

头痛来自第三个模型,因为每个fish都可以使用依赖于techniques的多个location来捕获。换句话说:fishtechnique之间的多对多关系会因每个location而发生变化。

我应该使用什么样的关联?

1 个答案:

答案 0 :(得分:2)

class Location < ActiveRecord::Base
  has_many :location_fishes
  has_many :fishes, :through => :location_fishes
end

class Fish  < ActiveRecord::Base
  has_many :location_fishes
  has_many :locations, :through => :location_fishes
end

class LocationFish < ActiveRecord::Base
  belongs_to :fish
  belongs_to :location

  has_and_belongs_to_many :techniques
end

请注意,可以改进模型和关系的名称。您还需要为这些创建适当的迁移,尤其是您不应忘记创建habtm连接表。

使用这些定义,您可以执行以下操作:

location = Location.find_by_name("Fancy lake")
some_fish = Fish.find_by_name("Trout")
techniques_for_location_and_fish = location.location_fishes.where(:fish_id => some_fish.id).first.techniques