首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >三种模型的非典型关联

问三种模型的非典型关联
EN

Stack Overflow用户
提问于 2012-08-22 11:00:01
回答 1查看 380关注 0票数 1

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

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

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

代码语言:javascript
复制
class Location < ActiveRecord::Base
    has_many :fish
end

每个fish可以在多个位置找到,因此:

代码语言:javascript
复制
class Fish < ActiveRecord::Base
    has_many :locations
end

第三种模型带来了麻烦,因为每个fish都可以使用依赖于location的多个techniques捕获。换句话说,在fish和technique之间存在着某种类似于多到多的关系,这种关系对于每个location来说都是不同的。

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-08-22 12:00:00

代码语言:javascript
复制
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连接表。

有了这些定义,您可以这样做:

代码语言:javascript
复制
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
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12071605

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档