Squeel 和 rails... 动态 where 子句

编程入门 行业动态 更新时间:2024-10-17 15:28:06
本文介绍了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") 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", first_name: "Deefour"}).to_sql

我会得到

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

更多推荐

Squeel 和 rails... 动态 where 子句

本文发布于:2023-10-23 05:33:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1519939.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:子句   动态   Squeel   rails

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!