我需要一个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发布于 2013-05-15 02:00:14
如果我理解正确的话,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-15 04:30:18
您应该使用: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
endhttps://stackoverflow.com/questions/16547556
复制相似问题