In Ransack, I will summarize how to use the select box.
First, I will explain the select
helper for creating select boxes.
select(object,Property name,Element information,option,Element attribute)
<%= f.select :name, [['sample1', 1], ['sample2', 2], ['sample3', 3]],
{include_blank: 'No selection'}, class: 'sample' %>
(Assuming that it is in form_for, it does not contain an object.)
In this way, if you put an array in the third argument, value 1 or 2 will be sent as a parameter
.
There is also a useful helper
to further customize the select box.
options_for_select
If you want to set the select box initial value
, use ʻoptions_for_select`.
options_for_select(Array/hash,option)
<%= 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. ``
options_from_collection_for_select
When you want to create choices from a model, it is convenient to use ʻoptions_from_collection_for_select`.
options_from_collection_for_select(Array of objects,value attribute,text item,option])
<%= f.select :name, options_from_collection_for_select(User.all, :id, :name , 1) %>
Now you can automatically make the name in the User model a select box.
Use ʻoptions_from_collection_for_select` as an 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 for' %>
<% end %>
By doing the above, you can search by using the name in the User model as a select box. In addition, the initial value is set as an option.
The _eq
part of name_eq
is called the matcher
and you can search for equal values.
There are also the following matchers.
matcher | meaning |
---|---|
_eq | equal |
noteq | Not equal |
_cont | Including value(LIKE) |
_iteq | Less than |
_gteq | that's all |
For more information, see the "Search Matchers" section of here.
https://railsguides.jp/form_helpers.html https://shinmedia20.com/rails-select-box
Recommended Posts