Squeel和rails …动态where子句
使用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"
您需要以编程方式构建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'))
我不知道这是否有帮助,但我使用这个帮助方法这样做:
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'}
然后我用一个循环中的链接来使用它:
query = SomeModel #could be User, etc dynamic_params.each_pair {|key,value| query = query.where(query_for_matches(key, value)) }
然后,您可以将query
传递给视图或其他任何内容。 我只在轨道上待了几个星期,所以我不确定这是不是最好的做法,但它确实有效。
- 在openshift上部署时,未初始化的常量ActionView :: Helpers :: ActiveModelHelper
- 将NTLM Active Directory用户数据检索到没有IIS的Rails
- 使用Minitest的Rails,如何使用rake运行每次测试时自动运行RuboCop?
- 活动记录按ID排序
- Link_to:method =>:删除不使用jQuery在Rails 3中进行路由销毁
- 如何调整在Heroku上运行的Ruby on Rails应用程序,它使用生产级Heroku Postgres?
- Rails 3 ActiveRecord交易
- Capybara匹配器存在按钮或链接
- ‘identify’命令无法识别Paperclip :: NotIdentifiedByImageMagickError图像