我在写一个关于钓鱼的应用程序。
fish模型。location模型。technique模型,其中包含了一些捕鱼技术。每个location可能有多个fish,因此:
class Location < ActiveRecord::Base
has_many :fish
end每个fish可以在多个位置找到,因此:
class Fish < ActiveRecord::Base
has_many :locations
end第三种模型带来了麻烦,因为每个fish都可以使用依赖于location的多个techniques捕获。换句话说,在fish和technique之间存在着某种类似于多到多的关系,这种关系对于每个location来说都是不同的。
我应该使用什么样的联想?
发布于 2012-08-22 12:00:00
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.techniqueshttps://stackoverflow.com/questions/12071605
复制相似问题