RT 请教大家一个问题,rails 怎么模糊查询 mysql2
用数组条件 Client.where("first_name LIKE ?", ['%', params[:first_name], '%'].join)
Client.where("first_name LIKE ?", ['%', params[:first_name], '%'].join)
@xworm 为什么不直接写: Client.where("first_name LIKE ?", "%#{params[:first_name]}%" ?
Client.where("first_name LIKE ?", "%#{params[:first_name]}%"
#2 楼 @killernova 都一样哈 并没有什么区别,现在喜欢这么写单纯只是为了强调一下 %
http://guides.ruby-china.org/active_record_querying.html 关于 active_record 查询
Question.where(Question.arel_table[:content].matches("%#{string}%"))
如果自己要动手弄 SQL 的话,推荐用 Arel 帮你生成更精美的 DSL。并且这玩意,貌似从 Rails3 开始就默认集成到 Rails 里面去了。
% xxx %这样查询是用不上索引的,如果表很大的话会把数据库搞得很累。
% xxx %
不如上搜索吧。
#6 楼 @xiaoronglv 然而人家的表不一定会很大。 几千几万的数据做好缓存的话硬搜没问题。
推荐参考一下railscasts-china
class Episode < ActiveRecord::Base scope :by_tag, lambda { |tag_name| joins(:tags).where("tags.name = ?", tag_name) unless tag_name.blank? } scope :by_keywords, lambda { |keywords| where("REGEXP_LIKE(episodes.name, ?,'i')", "#{keywords.split(" ").join('|')}") unless keywords.blank? } scope :published, lambda { where(publish: true) } end
class EpisodesController < ApplicationController def index @episodes = Episode.published.by_tag(params[:tag_id]).by_keywords(params[:query]).page(params[:page]) respond_to do |format| format.html format.rss end end end