1

釣りに関するアプリを書いています。

  • fishいくつかの種を含むモデルがあります。
  • location釣りスポットを含むモデルがあります。
  • techniqueいくつかの釣りテクニックを含むモデルがあります。

それぞれlocationに複数の がある場合がfishあるため、次のようになります。

class Location < ActiveRecord::Base
    has_many :fish
end

それぞれfishが複数の場所にあるため、次のようになります。

class Fish < ActiveRecord::Base
    has_many :locations
end

頭痛の種は 3 番目のモデルfishです。つまり、 と の間には、 ごとに変化する多対多の関係のようなものがあります。techniqueslocationfishtechniquelocation

どのような協会を利用すればよいですか?

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 に答える