Rails通过has_and_belongs_to_many属性进行过滤

时间:2022-10-01 00:16:00

I have a bit of a problem! I have a Place model and a Category model which are connected through has_and_belongs_to_many. I wish to be able to filter out all places which belong to atleast one of the categories in a given array (int array of ids). So far I've only been able to filter by a single category with the following code:

我有点问题!我有一个Place模型和一个Category模型,它们通过has_and_belongs_to_many连接。我希望能够过滤掉属于给定数组中至少一个类别的所有位置(int数组的id)。到目前为止,我只能使用以下代码按单个类别进行过滤:

@places = Place.find(:all, :include => :categories, :conditions => { "categories_places.category_id" => id})

so basically instead of id I want ids. I hope there are some rails experts here who can help! I'm very new to this.

所以基本上不是id我想要ID。我希望这里有一些铁道专家可以提供帮助!我对此很新。

3 个解决方案

#1


3  

This should do the trick nicely.

这应该很好地完成。

some_array_of_ids = [1, 2, 3]
@places = Place.find(:all, :include => :categories, :conditions => ['categories.id IN (?)', some_array_of_ids)

#2


0  

Try:

@places = Place.find(:all, :include => :categories, :conditions => ["categories_places.category_id IN ?", int])

where int - your array of ids

where int - 你的id数组

#3


0  

or if you want it in a scope for chaining

或者如果你想在链接的范围内

some_array_of_ids = [1,2,3]
@places = Place.includes(:categories).where('categories.id IN (?)', some_array_of_ids)

#1


3  

This should do the trick nicely.

这应该很好地完成。

some_array_of_ids = [1, 2, 3]
@places = Place.find(:all, :include => :categories, :conditions => ['categories.id IN (?)', some_array_of_ids)

#2


0  

Try:

@places = Place.find(:all, :include => :categories, :conditions => ["categories_places.category_id IN ?", int])

where int - your array of ids

where int - 你的id数组

#3


0  

or if you want it in a scope for chaining

或者如果你想在链接的范围内

some_array_of_ids = [1,2,3]
@places = Place.includes(:categories).where('categories.id IN (?)', some_array_of_ids)