0

It's not necessarily a has_many through but sorta maybe?

  • let's say modelA = Car Make
  • let's say modelB = Models
  • let's say modelC = Features

so I started with something like:

class CarMake < ActiveRecord::Base
  has_many :models
end

class Model < ActiveRecord::Base
  belongs_to :car_make
  has_and_belongs_to_many :features
end

class Feature < ActiveRecord::Base
  has_and_belongs_to_many :models
end  

I have the join tables correct and I have all the RESTful methods for CarMakes and Models working correctly, I can add Features to a Model and it saves correctly.

What I want to be able to do is display a Feature (which has attributes like name, cost, etc.) and list all the CarMakes that have that feature no matter what Model(s) it belongs to, I don't want to list the Models, just the CarMakes, is it possible?

CarMake has a one-to-many relationship with Models. Models and Features have a many-to-many relationship but there are no attributes or callbacks needed for that relationship. Indirectly CarMake has a many-to-many relationship with Features so perhaps I should just do it as a CarMake has_many Features through Models?

cordii
  • 35
  • 5

1 Answers1

0

You still need to go through each model for a given feature to get at the list of car_makes. This would probably result in duplicate listings, so .uniq filters those out again:

feature.models.map(&:car_make).uniq

If you declare the has_many :through association as you suggested (with uniq: true), you could simply do:

feature.car_makes

and ActiveRecord would generate an appropriate SQL query.

scivi
  • 106
  • 5