user1491929
user1491929

Reputation: 664

ActiveRecord: How to "select where in" on a has_many through association?

I have a Word object that has_many Categories through WordCategories

I want to get a list of words that have a relationship with the passed category ids.

In sql i would write

select * from words where category_id = (1,2,3,4)

Is it possible to do this but still bring back Word objects as a result?

edit

My example above is incorrect. I have a 3 Models,

Word has many dictionaries, and categories through dictionaries Category has many dictionaries, and words through dictionaries Dictionary belongs to Word and Dictionary

Upvotes: 1

Views: 215

Answers (2)

vee
vee

Reputation: 38645

You could join the three models as follows:

Word.joins(word_categories: :category).where(category: { id: [1, 2, 3, 4] })

or join word and word_categories and use word_categories.category_id in the where clause as:

Word.joins(:word_categories).where(word_categories: { category_id: [1, 2, 3, 4] })

Upvotes: 1

CDub
CDub

Reputation: 13344

ActiveRecord's where can take an array of IDs and search against that:

def self.with_category_ids(category_ids_array)
  where(:category_id => category_ids_array)
end

Would be a class method that returns all Word objects that have a category_id which is "in" category_ids_array.

Upvotes: 0

Related Questions