Amal
Amal

Reputation: 222

How to check with associated models

I have an Event model and a Service model I have to return Event records based on the parameters. I have two parameters city and service. City is present in Event model and service is the service name which is in the Service model. I have tried the following:

Event.all.map{|event| event.city == params[:city] && event.services.map{|service| service.where("lower(name) LIKE ?", "#{params[:service]} %")}}

But no luck so far if anyone could help that would be awesome. Thanks.

Upvotes: 2

Views: 246

Answers (1)

Sebastián Palma
Sebastián Palma

Reputation: 33420

You can use joins to add an INNER JOIN clause to your query and this way get access to the services related to each event. Having that, you can use their name column and filter them using ActiveRecord:

Event.joins(:services)
     .where(city: params[:city])
     .where('LOWER(services.name) LIKE ?', "#{params[:service]}%")

Upvotes: 2

Related Questions