simple_formの使い方

Railsのform_for内のコードをすっきりさせるsimple_formの使い方 - Rails Webook

 

上記を参考にsimple_formの使い方を学んだ。

<before>

<%= form_for(@product) do |f| %>
<% if @product.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@product.errors.count, "error") %> prohibited this product from being saved:</h2>

<ul>
<% @product.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>

<div class="field">
<%= f.label :name %><br>
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :price %><br>
<%= f.text_field :price %>
</div>
<div class="field">
<%= f.label :released_on %><br>
<%= f.date_select :released_on %>
</div>
<div class="field">
<%= f.label :rating %><br />
<%= f.radio_button :rating, 1 %> 1
<%= f.radio_button :rating, 2 %> 2
<%= f.radio_button :rating, 3 %> 3
<%= f.radio_button :rating, 4 %> 4
<%= f.radio_button :rating, 5 %> 5
</div>
<div class="field">
<%= f.label :discontinued %><br>
<%= f.check_box :discontinued %>
</div>
<div class="field">
<%= f.label :publisher_id %><br />
<%= f.collection_select :publisher_id, Publisher.all, :id, :name, include_blank: true %>
</div>
<div class="field">
<% Category.all.each do |category| %>
<%= check_box_tag "product[category_ids][]", category.id, @product.category_ids.include?(category.id), id: dom_id(category) %>
<%= label_tag dom_id(category), category.name %><br />
<% end %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>

<after>

<%= simple_form_for(@product) do |f| %>
<%= f.input :name %>
<%= f.input :price %>
<%= f.input :released_on %>
<%= f.input :rating %>
<%= f.input :discontinued %>
<%= f.association :publisher %>
<%= f.association :categories %>
<%= f.button :submit %>
<% end %>

<%= simple_form_for(@product) do |f| %>
<%= f.input :name %>
<%= f.input :price %>
<%= f.input :released_on %>
<%= f.input :rating %>
<%= f.input :discontinued %>
<%= f.association :publisher%>
<%= f.association :categories %>
<%= f.button :submit %>
<% end %>

 

使い方は簡単。

 

1.Gemfileに追加

gem 'simple_form'

 

2.bundle install

 

3.rails g simple_form:install

 

これをした後にafterのように書き換えればいい。