什么是包含在Rails查询LIKE子句的最好方法是什么? [英] What's the best way to include a LIKE clause in a Rails query?

查看:931
本文介绍了什么是包含在Rails查询LIKE子句的最好方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是包括沿(完全不正确的)的行Rails的查询,即东西LIKE子句的最佳方式:

  Question.where(:含量=>LIKE%耕作%)
 

解决方案

如果这是Rails 3中,你可以使用阿雷尔的匹配。这具有数据库无关的优点。例如:

  Question.where(Question.arel_table [:内容] .matches(%#{字符串}%))
 

这是有点笨重,但是很容易提取到的范围,如:

 类问题

  高清self.match_scope_condition(COL,查询)
    arel_table [COL] .matches(%#{查询}%)
  结束

  适用范围:匹配的lambda {| *的args |
    山坳,选择采用= args.shift,args.extract_options!
    OP = OPTS [:操作员] || :要么
    其中,args.flatten.map {|查询| match_scope_condition(COL,查询)} .inject(安培; OP)
  }

  适用范围:matching_content,拉姆达{| *查询|
    匹配(:内容,*查询)
  }
结束

Question.matching_content('养殖','跳舞')#耕作或跳舞
Question.matching_content('养殖','跳舞',:运营商=>:和)#耕作和舞蹈
Question.matching(:other_column,农业,跳舞)#同样的事情不同的关口
 

当然,加入与和你可以只链中的作用域。

编辑:+1 metawhere和squeel,但(没有试过后者,但它看起来很酷),他们都添加此类型的功能和更

What's the best way to include a LIKE clause in a Rails query i.e. something along the lines of (the completely incorrect):

 Question.where(:content => 'LIKE %farming%')

解决方案

If this is Rails 3 you can use Arel's matches. This has the advantage of being database agnostic. For example:

Question.where(Question.arel_table[:content].matches("%#{string}%"))

This is somewhat clunky, but easily extracted to scopes, e.g.:

class Question

  def self.match_scope_condition(col, query)
    arel_table[col].matches("%#{query}%")
  end

  scope :matching, lambda {|*args|
    col, opts = args.shift, args.extract_options!
    op = opts[:operator] || :or
    where args.flatten.map {|query| match_scope_condition(col, query) }.inject(&op)
  }

  scope :matching_content, lambda {|*query|
    matching(:content, *query)
  }
end

Question.matching_content('farming', 'dancing') # farming or dancing
Question.matching_content('farming', 'dancing', :operator => :and) # farming and dancing
Question.matching(:other_column, 'farming', 'dancing') # same thing for a different col

Of course to join with "AND" you could just chain the scopes.

Edit: +1 to metawhere and squeel though (haven't tried latter but it looks cool) They both add this type of functionality and much more.

这篇关于什么是包含在Rails查询LIKE子句的最好方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆