2011-06-21 116 views
1

我遇到了一些問題!我有通過has_and_belongs_to_many連接的Place模型和Category模型。我希望能夠過濾出屬於給定數組中至少一個類別的所有地方(int數組的ids)。到目前爲止,我只能夠通過一個單一的類別用下面的代碼進行過濾:Rails按has_and_belongs_to_many屬性過濾

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

所以基本上,而不是ID的我想要的ID。我希望這裏有一些能夠幫助的專家!我對此很陌生。

回答

3

這應該很好地訣竅。

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

謝謝你和@ bor1s爲快速反應。我不能嘗試解決方案,直到明天,但我毫不懷疑它應該工作:)不幸的是,我不能upvote,因爲太低代表:( – Cesar

0

嘗試:

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

其中int - 你的IDS

0

或數組,如果你想在一個範圍內的鏈接

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