使用 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 子句
发布评论