1
0

【Rails】テキストボックスの数を好きに増やしたり減らしたりしてみる

Last updated at Posted at 2024-02-10

どうもこんにちは。

今回は、Railsでフォームを作る時に使用するGemの「nested_form」について解説します。

テキストボックスの数を増やしたり減らしたりってどういうこと?

以下のようなフォームがあるとして、「追加」ボタンや「削除」ボタンをクリックしたときに、対象の要素を追加したり削除したりすることを今回は実現します。

スクリーンショット 2024-02-09 11.32.27.png

実装手順

1. Gem導入

Gemfile
gem 'nested_form`
bundle install

2. ビューファイルを作成する

app/views/content_groups/edit.html.erb
<%= nested_form_for @content_group, :url => {:action => :update} do |f| %>
    <%= f.link_to_add '追加', :content_groups, class: 'btn btn-success' %>
    <table class="table table-bordered">
        <tr>
            <th class="col-xs-6 col-ms-6 col-md-6 col-lg-6">グループ名</th>
            <td class="add_remove_button"></td>
        </tr>
    
        <%= f.fields_for :content_groups, :wrapper => false do |ff| %>
            <tr class="fields">
                <td><%= ff.text_field :name %></td>
                <td class="add_remove_button">
                    <%= ff.link_to_remove '削除', class: 'btn btn-warning' %>
                </td>
            </tr>
        <% end %>
    </table>
    
    <div class="footer_buttons">
        <%= f.submit '更新', class: "btn btn-primary", name: "update" %>
    </div>
<% end %>

解説

nested_form_forブロック内にあるlink_to_addは、link_to_addの第二引数と同じシンボルを持ったfields_forを追加します。

<!-- このボタンは -->
<%= f.link_to_add '追加', :content_groups, class: 'btn btn-success' %>

<!-- 以下のfields_forフォームを追加します -->
<%= f.fields_for :content_groups, :wrapper => false do |ff| %>
<% end %>

逆に、link_to_removeはこれが所属しているfields_forブロックを削除します。

<%= f.fields_for :content_groups, :wrapper => false do |ff| %>
    <tr class="fields">
        <td><%= ff.text_field :name %></td>
        <td class="add_remove_button">
            <!-- 以下のボタンをクリックすると、fields_for全体を削除します -->
            <%= ff.link_to_remove '削除', class: 'btn btn-warning' %>
        </td>
    </tr>
<% end %>
1
0
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
1
0