0

我需要一个 ActiveRecord 查询来匹配params[]数组中的所有项目。

我目前的方法是根据找到任何标签而不是“匹配所有”来给出结果

class Product < ActiveRecord::Base
    has_many :tags

    def self.filter_by_params(params)
        scoped = self.scoped
        scoped = scoped.includes(:tags).where(:tags => {:id => params[:t]}) if params[:t]
        scoped
    end
end

我试图写出类似下面的东西,但它没有给我任何结果。有人可以让我朝着正确的方向前进吗?有没有办法" AND "

def self.filter_by_params(params)
    scoped = self.scoped.includes(:tags)
    params[:t].each do |t|
        scoped = scoped.where(:tags => {:id => t})
    end
    scoped
end
4

2 回答 2

0

如果我理解正确,那params[:t]将是一个 ID 数组。如果是这种情况,您可以这样做:

def self.filter_by_params(params)
  scoped = self.scoped
  scoped = scoped.tags.find_all_by_id(params[:t])
  scoped
end

要不就:

def self.filter_by_params(params)
  tags.find_all_by_id(params[:t])
end
于 2013-05-14T18:00:14.380 回答
0

你应该使用 :joins 而不是 :includes

http://guides.rubyonrails.org/active_record_querying.html#specifying-conditions-on-the-joined-tables

class Product < ActiveRecord::Base
    has_many :tags

    def self.filter_by_params(params)
        scoped = self.scoped
        scoped = scoped.joins(:tags).where(:tags => {:id => params[:t]}) if params[:t]
        scoped
    end
end
于 2013-05-14T20:30:18.437 回答