RT 请教大家一个问题,rails 怎么模糊查询 mysql2
@xworm 为什么不直接写: Client.where("first_name LIKE ?", "%#{params[:first_name]}%"
?
http://guides.ruby-china.org/active_record_querying.html 关于 active_record 查询
Question.where(Question.arel_table[:content].matches("%#{string}%"))
如果自己要动手弄 SQL 的话,推荐用 Arel 帮你生成更精美的 DSL。并且这玩意,貌似从 Rails3 开始就默认集成到 Rails 里面去了。
推荐参考一下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