10
7

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 5 years have passed since last update.

【Rails】ヘルパーのcheck_boxで複数選択を登録

Last updated at Posted at 2019-04-16

備忘録用。 rails 5.2.3

Bookモデルにgenre(ジャンル)を
↓こんな感じでチェックボックスから複数選択して登録できるようにしたい。
スクリーンショット 2019-04-16 19.09.07.png

SFとドラマにチェックが入っているので、
ジャンルは**SF & ドラマ**ということになる。

view

ジャンルのリストは**@list_genre**に配列で格納されているとする。

new/edit.html.erb
<%= form_for(@book, class: 'form-horizontal', role: 'form') do |f| %>

・・・ 〜略〜
        <% @list_genre.each do |genre| %>
          <div>
            <%= f.check_box :genre,
                            { multiple: true,
                              checked: @book.genre.present? ? @book.genre.split(",").include?(genre) : false },  #・・・①
                              genre, nil %>
            <span><%= genre %></span>
          </div>
        <% end %>
・・・ 〜略〜

<% end %>

controller

books_controller.rb

  def new
    @book = Book.new
    @list_genre = LIST_GENRE
  end

  def create
    @book = Book.new(book_params)
    params[:book][:genre] ? @book.genre = params[:book][:genre].join(",") : false #・・・②
    if @book.save
      redirect_to book_path(@book.id)
    else
      @list_genre = LIST_GENRE
      render :new
    end
  end

edit,updateも似たような感じで・・・

補足

①: checked: によりeditの時、マッチしていればチェックが入る。
  stringのinclude?では部分一致でマッチしてしまうのでsplit(",")でArrayにしている。
②:genreはデータ型がstringなのでjoin(",")して**"SF, ドラマ"**という形で格納させる必要がある。

思っていること

Stringにしてsaveしたり、split(",")でArrayに戻したりと、ゴテゴテしていて美しくない気がする。
もっとうまいやり方はないものか。

結論:これ使えばいいのかもhttps://qiita.com/RaimuEr/items/58971510735c6b906c50

参考:https://qiita.com/tomoima525/items/22c215db90cc9a9b09cc

10
7
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
10
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?