Uj Corb
Uj Corb

Reputation: 2189

Filter from a table Active Record

I have two tables: Restaurant and Meal

restaurant has_many meals and meal belongs_to restaurant. Hence each meal has a restaurant_id column.

I have a @meals_search variable in my controller that is a list of meals from a search of a user in a search bar.

I want to display the restaurants corresponding to the @meals_search.restaurant_id but so far I can't find the right ActiveRecord query.

For example, if @meals_search.pluck(:restaurant_id) is equal to [1,7,44,53], then I want to create a @restaurants variable that stores restaurants with id 1,7, 44 and 53.

I populate the @meals_search variable like this:

meals_controller.rb

@meals_search = @meals.search(params[:search])

model.meal.rb

  belongs_to :restaurant

def self.search(search)
  if search
    where('name LIKE ?', "%#{search}%")
  else
    all
  end
end

Any idea ?

Upvotes: 0

Views: 405

Answers (3)

Mikhail Katrin
Mikhail Katrin

Reputation: 2384

You can also use map insted of pluck

@restaurants = Restaurant.where(id: @meals_search.map {|m| m.restaurant_id})

Upvotes: 1

Marek Lipka
Marek Lipka

Reputation: 51181

If I understand your problem correctly, you simply need to do this:

@restaurants = Restaurant.where(id: @meals_search.pluck(:restaurant_id))

This uses ActiveRecord subset conditions.

The above query translates to something like:

SELECT * FROM Restaurant WHERE (restaurant.in IN (1,3,5))

Upvotes: 1

ghstcode
ghstcode

Reputation: 2912

If I understand your question correctly, you want something like this?

@restaurants = Restaurant.where(id: @meals_search.pluck(:restaurant_id))

Upvotes: 1

Related Questions