Skip to content

Instantly share code, notes, and snippets.

@budougumi0617
Created July 13, 2014 12:29
Show Gist options
  • Save budougumi0617/c48a5cc82db9353dcefc to your computer and use it in GitHub Desktop.
Save budougumi0617/c48a5cc82db9353dcefc to your computer and use it in GitHub Desktop.
Ruby on Rails4で複数キーワードのOR検索をしたいときはArelを使う。 ref: http://qiita.com/budougumi0617/items/e6102f0d424d4031f7e2
for i in 1...keyword_arrays.length
seminars_sel = seminars_sel.or(seminars.matches("\%#{keyword_arrays[i]}\%"))
end
<div id="condition-cards" class="clearfix">
<%= form_tag seminars_path, :method => 'get' do %>
<div id="keyword">
<dl class="clearfix">
<dt><%= text_field_tag :search, params[:search] %></dt>
<dd><%= submit_tag "検索", :name => nil %></dd>
</dl>
</div>
<% end %>
</div>
ActiveRecord::Schema.define(version: 20140713000000) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "seminars", force: true do |t|
t.string "summary"
end
end
# encoding: utf-8
class Seminar < ActiveRecord::Base
def self.search(params)
params[:search] ||= ""
keyword_arrays = params[:search].gsub(/ /," ").split()
seminars = Seminar.arel_table[:summary]
seminars_sel = seminars.matches("\%#{keyword_arrays[0]}\%")
for i in 1...keyword_arrays.length
seminars_sel = seminars_sel.or(seminars.matches("\%#{keyword_arrays[i]}\%"))
end
logger.debug("SQL: #{Seminar.where(seminars_sel).to_sql}")
Seminar.where(seminars_sel)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment