Tag: Ransack
gem "ransack"
def index @search = Item.ransack(params[:q]) @items = @search.result end
※searchじゃなくてransackメソッドのほうが推奨になったらしい(公式サイト)
<%= search_form_for @search do |f| %> <%= f.text_field :title_cont %> <%= f.submit '検索' %> <% end %> <% @items.each do |item| %> (省略) <% end %>
>> User.ransack(first_name_or_last_name_cont: 'Rya').result.to_sql => SELECT "users".* FROM "users" WHERE ("users"."first_name" LIKE '%Rya%' OR "users"."last_name" LIKE '%Rya%')
User.search( g: { '0' => { m: 'or', power_gteq: 100, magic_gteq: 30 }, '1' => { m: 'and', level_gteq: 20, hp_lteq: 30 } } ).result
def search_form_for(record, options = {}, &proc)
<%= search_form_for(@search) do |f| %>
<%= search_form_for(@search, url: items_path, html: {class: 'form-inline'}) do |f| %>
@search = Post.ransack(params[:q]) @search.sorts = 'name asc' if @search.sorts.empty? #一つの場合 @search.sorts = ['name asc', 'created_at desc'] if @search.sorts.empty? # 複数の場合 @posts = @search.result.paginate(page: params[:page], per_page: 20)
params[:q][:s] = "rating desc"
@search.result.order("rating desc")
<%= sort_link(@q, :name, 'Last Name', default_order: :desc) %>
<%= sort_link(@q, :last_name, %i(last_name first_name), default_order: { last_name: 'asc', first_name: 'desc' }) %>
params[:q][:s] = build_sql(params[:sort_order])
<%= select_tag("q[complex_cond]", options_for_select()..) %>
if complex_cond == '1' @search.title_eq ='あああ' end