Dragon Arrow written by Tatsuya Nakaji, all rights reserved animated-dragon-image-0164

Rails simple_formの導入

updated on 2018-12-08

イメージ

simple_formを導入して簡単にフォームを作れる様にする

1.

#Gemfile
...
gem 'simple_form'
$ bundle install


step2 simple_formの設定ファイルをインストール

$ rails generate simple_form:install

Simple Formにbootstrapも適用したいいとはこちら!!

$ rails generate simple_form:install --bootstrap


使い方はこちらの方こちらの方が見やすいです


formを作る

# _form.html.erb

<%= simple_form_for (@article) do |f| %>
  <% if @article.errors.any? %>
    <div id="error_explanation">
      <h2>
        <%= "#{pluralize(@article.errors.count, "error")}個のエラーで保存ができません" %>
      </h2>
      <ul>
        <% @article.errors.full_messages.each do |msg| %>
          <li>
            <%= msg %>
          </li>
          <% end %>
      </ul>
    </div>
  <% end %>

  <div class="form-group">
    <%= f.input :title, label: "タイトル" %>
  </div>

  <div class="form-group">
    <%= f.input :body, label: "内容" %>
  </div>

  <div class="form-group">
    <%= f.input :image, as: :file, class: "form-control" %>
  </div>
  <div class="form-group">
    <%= f.button :submit %>
  </div>

 

formのcssを作る(自分の好きなレイアウトに)

#stylesheets/form.scss
.simple_form {
label {
margin: 2px 10px;
&.radio, &.checkbox {
float: none;
margin: 0;
width: auto;
text-align: left;
}
&.checkbox {
display: block;
}
&.radio { margin-right: 10px; }
}
div.input { margin-bottom: 10px;}
input.radio_buttons, input.check_boxes {
margin-right: 5px;
}
.alert-error {
color: #D00;
margin-bottom: 10px;
font-weight: bold;
}
.hint, .error {
clear: left;
font-size: 12px;
color: #D00;
display: block;
}
.hint {
color: #555;
font-style: italic;
}
}


simple_formを使えば記述は多少少なくなるけど、正直、あまり導入しなくてもいいかなって感じではある...


こっちの方が個人的には好き


#_form.html.erb

<%= form_with(model: post, local: true) do |form| %>
<% if post.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(post.errors.count, "error") %> 保存できません</h2>

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

<div class="field">
<%= form.label :title %>
<%= form.text_field :title, class: 'form-control' %>
</div>

<div class="field">
<%= form.label :body %>
<%= form.text_field :body, class: 'form-control' %>
</div>

<div class="field">
<%= form.label :image %>
<%= form.file_field :image, class: 'form-control' %>
</div>

<div class="actions">
<%= form.submit '更新する', class: 'btn btn-block btn-success' %>
</div>
<% end %>
articles_controller

def new
@article = Article.new
end

def edit
@article = Article.find(params[:id])
end

def create
  @article = Article.new(article_params)
  if @article.save
  flash[:notice] = "作成に成功しました"
  redirect_to article_path(@article)
  else
  flash[:alert] = "エラーのより保存できませんでした"
  render :new
  end
end

private 

def article_params
  params.require(:article).permit(:title, :body, :image)
end

new.html.erb edit.html.erb
<%= render 'form', post: @article %>