如何使用ActiveRecord匹配所有“和”?

时间:2013-05-14 15:47:40

标签: ruby-on-rails ruby ruby-on-rails-3 activerecord

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

我当前的方法基于找到任何标签而不是“MATCH ALL”

来给出结果
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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

你应该使用:join而不是: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