我有三个"1到n“关联的模型,如下所示
Client --1 to n--> Category --1 to n-> Item
在一个页面中,我需要显示一个项目列表以及它们的类别。此页面受3级过滤的限制:
我越来越困惑于ActiveRecord协会之类的东西
在我的ItemsController#index中,我尝试了这个:
categories = Client.find(2).categories
.where('name LIKE ?', "%#{params[:filter_categories]}%")
@items = categories.items
.where('name LIKE ?', "%#{params[:filter_items]}%")第二行引发一个NoMethodError undefined method 'items' for ActiveRecord::Relation。我知道第一行返回一个Relation对象,但是我无法找到从这里继续并获得链接到这个类别列表的项目列表的方法。
我还开始提取第一行返回的类别I列表,以便在第二行的where子句中使用它们,但在编写代码时,我发现它不优雅,认为可能有更好的方法。任何帮助都将不胜感激。谢谢
models/client.rb
class Client < ActiveRecord::Base
has_many :categories
has_many :items, through: :categories
...
endmodels/category.rb
class Category < ActiveRecord::Base
belongs_to :client
has_many :items
...
endmodel/item.rb
class Item < ActiveRecord::Base
belongs_to :category
has_one :client, through: :category
...
end发布于 2013-03-13 13:00:21
只能在类别对象上调用.items,而不能在集合上调用。这样做是可行的:
@items = categories.first.items
.where('name LIKE ?', "%#{params[:filter_items]}%")为了得到你想要的,你可以做以下几件事:
@items = Item
.where('category_id IN (?) AND name LIKE ?', categories, "%#{params[:filter_items]}%")假设最终您只对@items中的内容感兴趣,那么使用joins在一个查询中而不是在两个查询中进行更好的操作。
@items = Item.joins(:category)
.where('items.name LIKE ? AND categories.name = ? AND categories.client_id = 2', "%#{params[:filter_items]}%", "%#{params[:filter_categories]}%")发布于 2013-03-13 13:02:36
你可以试试这样的方法:
item_ids = Client.find(2).categories.inject([]) { |ids, cat| ids |= cat.item_ids; ids }
items = Item.find(item_ids)这是如何获得通过另一个表关联的嵌套对象的列表。
https://stackoverflow.com/questions/15385916
复制相似问题