Squeel和rails ...动态where子句

时间:2013-02-01 19:56:42

标签: ruby-on-rails ruby-on-rails-3 squeel

使用Squeel,在rails应用程序中,我有一个条件哈希:

{'trans' => 'manual'}

我最终计划进入一个数组...所以我也可以进行操作员分配。

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

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

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"

2 个答案:

答案 0 :(得分:3)

您需要以编程方式构建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'))

答案 1 :(得分:0)

我不知道这是否有帮助,但我是这样用这个辅助方法做的:

  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传递给您的视图或其他任何内容。我只在轨道上工作了几个星期,所以我不确定这是否是最佳实践但它确实有效。