enum定義
customer.rb
enum status: { not_app: 0, app: 1 , cancel: 2}
statusの型はinteger
参考:https://qiita.com/shizuma/items/d133b18f8093df1e9b70
customer.rb
def self.search(params)
customers = customers.where(status: params[:status]) if params[:status].present?
end
検索(コントローラ)
customers_controller.rb
def index
@customers = Customer.search(params)
end
検索(ビュー)
index.html.erb
<%= form_tag( {:action => :index}, :method => :get) do %>
===========================
# ラジオボタンの時
<tr>
<th scope="row">ステータス</th>
<td>
<%= radio_button_tag :status, 1, params[:status] %><label
for="status_1">有効会員</label>
<%= radio_button_tag :status, 0, params[:status] %><label
for="status_0">退会済</label>
<%= radio_button_tag :status, 2, params[:status] %><label
for="status_2">ブラック会員</label>
</td>
===========================
# セレクトボッックスの時
<tr>
<th scope="row">ステータス</th>
<td colspan="3">
<%= select_tag :status, Customer.statuses.keys.map {|k| [I18n.t("enums.customer.status.#{k}"), k]} %>
</td>
</tr>
===========================
<% end %>
gemインストール
gemfile.
gem 'enum_help'
$ bundle install
日本語化
ja.yml
enums:
customer:
status:
app: 有効会員
not_app: 退会済
cancel: ブラック会員
#これ書かないとセレクトボックスのところでちゃんと表示されない
受け取ったstatustの値が見たいときはstatus_i18n
で表示できる
参考:(i18n): https://tech.misoca.jp/entry/2015/08/10/132419
参考(select): https://qiita.com/HrsUed/items/56677d6c266d8a53ffa7