使用Squeel,在rails应用程序中,我得到了一系列条件:
{'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"发布于 2013-02-02 04:21:14
您需要以编程方式构建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'))发布于 2014-01-03 20:12:33
我不知道这是否有帮助,但我是使用这个helper方法这样做的:
def query_for_matches(key, value)
stub = Squeel::Nodes::Stub.new(key)
Squeel::Nodes::Predicate.new(stub, :matches, "%#{value}%")
end你有一个散列的参数,来自某个东西的请求:
dynamic_params = {'username' => 'some_name', 'email' => 'email@example.com'}然后,我在一个循环中使用一系列where:
query = SomeModel #could be User, etc
dynamic_params.each_pair {|key,value| query = query.where(query_for_matches(key, value)) }然后,您可以将query传递给您的视图或其他任何东西。我在rails上只用了几个星期,所以我不确定这是否是最佳实践,但它是有效的。
https://stackoverflow.com/questions/14654010
复制相似问题