Reputation: 1004
I have some trouble writing some code (I might be tired), so I need some help here!
I have a model Wedding which has multiple Services through a join table. It is a Many-to-Many relationship. And each of these Services have a specific service_type.
So basically I can do something like that:
myWeddingObject.services.first.service_type
My problem is that I would like to be able to get directly all the services types available for a wedding. For example:
myWeddingObject.service_types
And my question is, Am I obliged to write a method in my Wedding model where I would fetch all the services and check their types and then collect it or is there an other way that I did not see at first?
I thought of writing something like that in the Wedding model:
has_many :service_types, :through => :services
But as you can presume, it doesn't work. I might also have to add another model/SQL table?
I hope I have been clear enough and thanks for your help, I appreciate!
Upvotes: 0
Views: 74
Reputation: 831
The easy way is to just do
wedding.services.map(&:service_type).uniq
...Which will return an array of the service types. If you want has_many :through to work then you need to make service_type its own model. If you have a ton of service types that you want to be adding and editing, then a model is clearly the way to go. If it's just a small fixed set, then a separate model is probably overkill.
Upvotes: 2