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 %>
gem "validate_url"
class User < ActiveRecord::Base validates :homepage, url: { allow_blank: true } end
../Bootstrapを参照のこと。
# GET /items/new def new @item = Item.new end # GET /items/1/edit def edit end # POST /items # POST /items.json 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 # PATCH/PUT /items/1 # PATCH/PUT /items/1.json def update respond_to do |format| if @item.update(item_params) format.html { redirect_to @item, notice: 'Item was successfully updated.' } format.json { render :show, status: :ok, location: @item } else format.html { render :edit } format.json { render json: @item.errors, status: :unprocessable_entity } end end end