albertedevigo
albertedevigo

Reputation: 18411

Atypical association of three models

I'm writing an app about fishing.

Each location may have multiple fish, so:

class Location < ActiveRecord::Base
    has_many :fish
end

Each fish can be found in multiple locations, so:

class Fish < ActiveRecord::Base
    has_many :locations
end

The headache comes with the third model, because each fish can be caught with multiple techniques that depend on the location. In other words: there is something like a many-to-many relationship between fish and technique that changes for each location.

What kind of association should I use?

Upvotes: 1

Views: 382

Answers (1)

socjopata
socjopata

Reputation: 5095

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

Please note that names of models and relations could be improved. Also you need to create proper migrations for these, especially you should not forget about creating habtm joining table.

With these definitions you can do something like this:

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

Upvotes: 2

Related Questions