gpt4 book ai didi

ruby-on-rails - Squeel 和 rails... 动态 where 子句

转载 作者:行者123 更新时间:2023-12-04 05:58:35 25 4
gpt4 key购买 nike

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

{'trans' => 'manual'}

我最终计划将其移动到数组中...这样我也可以进行运算符赋值。

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

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

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

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

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

在控制台中:

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

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

最佳答案

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

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 模型上我可以运行

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'))

关于ruby-on-rails - Squeel 和 rails... 动态 where 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14654010/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com