0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Rail enumで2択のデータを保存する方法(integer型)

Last updated at Posted at 2020-04-03

 概要

こんにちは。
個人アプリの作成過程でラジオボタンで2択のデータを保存する機能を実装したので、残しておきます。
今回はMaterializeを使用しています。

こんな感じです。

Screenshot from Gyazo

手順

  • integer型でカラムを作成
  • モデルにenumを記述
  • view側に記述

integer型でカラムを作成

ポートフォリオでカフェを投稿するアプリを作成したので今回は

wifiカラムをinteger型で作成します。

add_columnn.rb
  def change
    add_column :shops, :wifi, :integer
  end

モデルにenumを記述

shop.rb
  enum wifi: { yes: 1, no: 2 }

コンソールでは

pry(main)> @shop.wifi = 1
=> 1
pry(main)> @shop.wifi
=> "yes"

このようにenumに設定したvalueが出力されます。

viewに記述

form_forでラジオボタンからデータを送ります。

<%= form_for(@shop) do |f| %>
  <%= f.radio_button :wifi, :yes %> # チェックすると1が入る
  <%= f.radio_button :wifi, :no %> # チェックすると2が入る
<% end %>

私はmateriarizeで実装したのでこんな感じになりました。

<%= form_for(@shop) do |f| %>
  <div class="col s12 radio_col">
    <label>
      <span class="list">Wifi</span>
      <i class="material-icons small">wifi</i>
      <%= f.radio_button :wifi, :yes, class: "with-gap"%>
      <span></span>
    </label>
    <label>
      <%= f.radio_button :wifi, :no, class: "with-gap"%>
      <span></span>
    </label>
  </div>
<% end %>

表示は

<% @shop.wifi %>
valueが1なら
"yes"
valueが2なら
"no"
と表示される

if文では

<% if shop.wifi == "yes" %>

と書く
== 1ではfalseになってしまいました。

また,enum時点で文字列でも設定できるみたいです!

次回はJqueryで選択解除する方法をあげたいとおもいます!

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?