[Ruby] [Rails] How to use select box in Ransack

1 minute read


In Ransack, I will summarize how to use select boxes.

About #select First, I will explain the select helper for creating a select box.

Basic type

select (object, property name, element information, option, element attribute)

Implementation example

<%= f.select :name, [['sample1', 1], ['sample2', 2], ['sample3', 3]],
 {include_blank:'No selection'}, class:'sample' %>

(Assuming that it is inside form_for, it does not contain any objects.) Thus, if you put an array in the third argument, value 1 or 2 will be sent as a parameter.

Useful helpers

There is also a convenient helper to customize the select box.


Use options_for_select to set the default value of the select box.

Basic form

options_for_select (array/hash, options)

Implementation example

<%= f.select :name, options_for_select({sample1: 1, sample2: 2, sample3: 3}, 1),
 include_blank: true %>

Since “1” is included in the second argument of options_for_select, 1 is displayed as the default value.


Use options_from_collection_for_select when you want to create choices from the model.

Basic form

options_from_collection_for_select( array of objects, value attribute, text item, options])

Implementation example

<%= f.select :name, options_from_collection_for_select(User.all, :id, :name ,1) %>

With this, the name in the User model can be automatically made a select box.

How to use #Ransack

Use options_from_collection_for_select as an example.

Implementation example

<%= search_form_for(@q, url: users_path, local: true) do |f| %>

  <%= f.select :name_eq, options_from_collection_for_select(User.all, :id, :name ,1) %>

  <%= f.button'Search' %>

<% end %>

By doing the above, you can search using the name in the User model as the select box. Also, an initial value is set as an option.

The _eq part of name_eq is called matcher and you can search for equal values.

About Matcher

There are also the following matchers.

matcher Meaning
_eq equal
noteq Not equal
_cont Contains value (LIKE)
_iteq Below
_gteq Above

For more information, see the “Search Matchers” section on here.


https://railsguides.jp/form_helpers.html https://shinmedia20.com/rails-select-box