1

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

  • 我们有一个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.

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

4

1 回答 1

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
于 2012-08-22T12:00:00.567 回答