Squeel 和 rails... 动态 where 子句 [英] Squeel and rails... dynamic where clause

查看:52
本文介绍了Squeel 和 rails... 动态 where 子句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Squeel,在 Rails 应用程序中,我有一个条件散列:

Using Squeel, in a rails app, I have a hash of conditions:

{'trans' => 'manual'}

我最终计划移动到一个数组中...所以我也可以有一个运算符赋值.

which i eventually plan on moving into an array... so i can also have an operator assignment.

[[field,operator,value][field,operator,value]]

我想使用模型方法,现在我省略了操作符,我只是想 == 让它工作......但是,我下面的方法不起作用.

I want to use a Model method, which for now i omit the operator and am I just trying == to get this to work... however, what i have below does not work.

def self.with_conditions(conditions)
    joins{car}.where do
      conditions.map {|key,value| (key==value) }.inject(:&)
    end
end

我也试过这个:

def self.with_conditions(conditions)
  joins{car}.where do
    query = nil

    conditions.each do |key, value|
      q = (key == value)

      if query
        query &= q
      else
        query = q
      end
    end

    query     
  end
end

那么,我如何让它与 == 一起工作,然后我最终如何让它与动态运算符一起工作?谢谢

So, how do i get this to work with the ==, and then how would i eventually get this to work with a dynamic operator as well? thanks

在控制台中,我的 SQL 没有读取我的任何条件...例如:

In console, my SQL doesn't read in any of my conditions... for example:

在控制台中:

> Timeslip.with_conditions({'car.year'=>'1991'})

SELECT "timeslips".* FROM "timeslips" INNER JOIN "cars" ON "cars"."id" = "timeslips"."car_id"

推荐答案

您需要以编程方式构建 Squeel 查询.例如:

You need to programmatically build the Squeel query. For example:

def self.with_conditions(conditions)
  conditions.map do |col, str|
    Squeel::Nodes::Predicate.new(Squeel::Nodes::Stub.new(col), :matches, str) # (email.matches "user@example.com")
  end.inject do |t, expr|
    t & expr # joins each expression from the .map above with & - to be converted to AND in the sql
  end.tap do |block|
    return where{(block)} # pass the constructed expression to Squeel
  end
end

在我的 User::User 模型上我可以运行

On my User::User model I can run

User::User.with_conditions({email: "user@example.com", first_name: "Deefour"}).to_sql

我会得到

SELECT "user_users".* FROM "user_users"  WHERE (("user_users"."email" LIKE 'user@example.com' AND "user_users"."first_name" LIKE 'Deefour'))

这篇关于Squeel 和 rails... 动态 where 子句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆