Tag: Rails/検証
class Item < ActiveRecord::Base validates :title, presence: true end
def create @item = Item.new(item_params) respond_to do |format| if @item.save format.html { redirect_to @item, notice: 'Item was successfully created.' } format.json { render :show, status: :created, location: @item } else format.html { render :new } format.json { render json: @item.errors, status: :unprocessable_entity } end end end
<%= form_for(@item) do |f| %> <% if @item.errors.any? %> <div id="error_explanation"> <h2>エラーが発生しました :</h2> <ul> <% @item.errors.full_messages.each do |msg| %> <li><%= msg %></li> <% end %> </ul> </div> <% end %> <div class="field"> <%= f.label :title %><br> <%= f.text_field :title %> </div> <div class="field"> <%= f.label :content %><br> <%= f.text_area :content %> </div> <div class="actions"> <%= f.submit %> </div> <% end %>