Created
July 13, 2014 12:29
-
-
Save budougumi0617/c48a5cc82db9353dcefc to your computer and use it in GitHub Desktop.
Ruby on Rails4で複数キーワードのOR検索をしたいときはArelを使う。 ref: http://qiita.com/budougumi0617/items/e6102f0d424d4031f7e2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| for i in 1...keyword_arrays.length | |
| seminars_sel = seminars_sel.or(seminars.matches("\%#{keyword_arrays[i]}\%")) | |
| end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <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> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 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