Ruby ActiveRecord:通过多个实例查找

Ruby ActiveRecord:通过多个实例查找,ruby,ruby-on-rails-3,activerecord,Ruby,Ruby On Rails 3,Activerecord,假设我的控制器中有以下各项: @category1 @category2 我想找到与这两个类别相关的所有商店 @stores = @category1.stores + @category2.stores 这确实有效,但不幸的是返回一个未更改的数组,而不是AR::Base数组,因此,我无法执行分页、作用域等操作 在我看来,似乎有一种通过多实例关联进行查找的内置方式。。。不是吗?使用ActiveRecord,每当您找到一组独特的模型对象时,调用该模型上的find通常是您的最佳选择 #@stor

假设我的控制器中有以下各项:

@category1
@category2
我想找到与这两个类别相关的所有商店

@stores = @category1.stores + @category2.stores
这确实有效,但不幸的是返回一个未更改的数组,而不是AR::Base数组,因此,我无法执行分页、作用域等操作


在我看来,似乎有一种通过多实例关联进行查找的内置方式。。。不是吗?

使用ActiveRecord,每当您找到一组独特的模型对象时,调用该模型上的find通常是您的最佳选择

#@stores = @category1.stores + @category2.stores
#if you want to call API methods you can just add conditions with the category id
@stores = Store.find(:all, :conditions => ['category_id=?', a || b])
然后,您所需要做的就是用您关心的类别约束联接表

@stores = Store.all(:joins => :categories,
                    :conditions => ['category_stores.category_id in (?)', [@category1.id, @category2.id]])

我不能这样做,因为商店有很多类别,并且通过一个联接表关联。你有没有让它工作过?我在做类似的事情时遇到了困难: