我正在写一个关于钓鱼的应用程序。
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
来捕获。换句话说:fish
和technique
之间的多对多关系会因每个location
而发生变化。
我应该使用什么样的关联?
答案 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