【问题标题】:Atypical association of three models三种模型的非典型关联
【发布时间】:2012-08-22 11:00:01
【问题描述】:

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

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

每个location可能有多个fish,所以:

class Location < ActiveRecord::Base
    has_many :fish
end

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

class Fish < ActiveRecord::Base
    has_many :locations
end

第三种模型让人头疼,因为每个fish 都可以被多个依赖locationtechniques 捕获。换句话说:fishtechnique 之间存在类似多对多的关系,每个location 都会发生变化。

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

【问题讨论】:

  • 技术和鱼有关系还是只是位置和技术的关系。你能举个更准确的例子吗?
  • 当然!我想钓 SHARKS(鱼),在 BLUEDEEPS(位置)我可以钓到 SPEARFISHING(技术)或 CASTING(技术)。在 GREENROCK(位置​​),我可以用 CASTING(技术)或 NET(技术)捕鱼。但在 GREENROCK(位置​​),我可以通过 SPEARFISHING(技术)钓鲈鱼(鱼)。是的,它是一个关联三角形......

标签: ruby-on-rails activerecord model associations


【解决方案1】:
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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多