Reputation: 279
I'm a bit stuck trying to build what seems like a rather complex query and hope somebody can point me at the right direction.
Model Project
has 2 has_many through relationships to model Sector
and model Service
.
what i want to achieve is something like:
/projects?service_ids[]=1§or_ids[]=1§or_ids[]=2
where essentially i want to get only the projects which have service 1 and sectors 1 and 2, for example.
I know that due to the has_many through relationship, i can get the projects under a service or sector. But to do that i need to first fetch a service/sector. In this case however, i feel i need to get projects and filter based on the relationships. I'm just not sure how i'd go about doing that.
I hope i managed to explain it properly. Do let me know if you need any extra info.
EDIT:
To clarify a bit, if no service_ids is passed on params, than i want to check the sector_ids. now, if both sector_ids and service_ids are passed, i need to filter all the projects to get ONLY the projects that have a relationship to both the services with passed ids and sectors with passed ids.
Thanks a lot
Upvotes: 0
Views: 64
Reputation: 1174
Please try below query to get details from both services and sectors table
Project.joins(:services, :sectors).where("services.id in (?) and sectors.id in (?)", params[:service_ids], params[:sector_ids])
Upvotes: 1