【问题标题】:How do I match all "and" using ActiveRecord?如何使用 ActiveRecord 匹配所有“和”?
【发布时间】:2013-05-14 15:47:39
【问题描述】:

我需要一个 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

【问题讨论】:

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


    【解决方案1】:

    如果我理解正确,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
    

    【讨论】:

    • 是的,它只是一个 ID# 的数组...但是,您的解决方案对我不起作用...
    • 当我尝试您的解决方案 #2 时,我收到消息 undefined local variable or method `tags' for #<0x007fbded6a70b8>
    【解决方案2】:

    你应该使用 :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
    

    【讨论】:

    • 这仍然不能“全部匹配”,如果它在参数中找到任何标签,它就会返回它
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-27
    • 2010-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多