mc9
mc9

Reputation: 6349

How to use OR in Rails 4 ActiveRecord named scope

I have course and category models in my project. Course has many categories and category has many courses.

In course model, I have a scope :search_by_category that will take in a name of category, and find the course where the course's category name is equal to the name.

scope :search_by_category, -> (name){
  joins(:categories).where('categories.name = ?', name) if name.present?
}

The scope works fine if I have a single name. But when I have an array of names, it breaks, because where('categories.name = ?', "Some name", "Some other name", "Some more name") is an invalid SQL syntax.

After I experimented with rails console, I find that I need to use OR.

e.g.

where('categories.name = name[0] OR categories.name = name[1])

How can I rewrite my scope to achieve this, or are there any other ways that I can try?

Upvotes: 0

Views: 80

Answers (2)

Roman Kiselenko
Roman Kiselenko

Reputation: 44370

Try this:

array_with_names = ["Some name", "Some other name", "Some more name"]
where('categories.name in (?)', array_with_names)

If you want use OR operator, make array with names and use * splat operator:

array_with_names = ["Some name", "Some other name", "Some more name"]
where('categories.name = ? OR categories.name = ? OR categories.name = ?', *array_with_names)

But i think this useless.

Upvotes: 2

konole
konole

Reputation: 766

Use Rails syntax for this. ActiveRecord will automatically detect you are using array and will construct proper SQL syntax for you (whether to use IN or =).

scope :search_by_category, -> (array_with_names){
  joins(:categories).where(categories: { name: array_with_names })
}

Upvotes: 1

Related Questions