2016-03-06 61 views
0

問題:我想打password & password_confirmation領域validates presence:truecreate行動和update行動設計CRUD驗證

guest.rb沒有驗證:

class Guest < ActiveRecord::Base 
    devise :database_authenticatable, :recoverable, :rememberable, :trackable 
    validates :email, presence: true 
end 

我guests_controller.rb:

class GuestsController < ApplicationController 

    before_action :set_guest, only: [:show, :edit, :update] 

    def index 
    @guests = Guest.all 
    end 

    def show 
    @guest = Guest.find(params[:id]) 
    end 

    def new 
    @guest = Guest.new 
    end 

    def edit 
    @guest = Guest.find(params[:id]) 
    end 

    def create 
     respond_to do |format| 
     format.html do 
      @guest = Guest.new(guest_params) 
      if @guest.save 
      redirect_to guests_path, notice: 'Client was successfully created.' 
      else 
      render :new 
      end 
     end 
     end 
    end 

    def update 
    @guest = Guest.find(params[:id]) 
    if @guest.update_attributes(guest_params) 
     sign_in(@guest, :bypass => true) if @guest == current_guest 
     redirect_to guests_path, notice: 'Client was successfully updated.' 
    else 
     render :edit 
    end 
    end 

如果我把validates :password, presence: true,它影響一切,而我需要它僅適用於create

回答

5

Active Record Validations Guide

:on選項可以指定當驗證應該發生。所有內置驗證助手的默認行爲是在保存時運行(無論是在創建新記錄還是在更新時)。如果要更改它,則可以使用::create僅在創建新記錄時運行驗證,或者僅在更新記錄時運行驗證纔可運行on: :update

所以你的情況,你可以使用:

validates :email, presence: true, on: :create 

我建議你花一點時間坐下來,通過整個指南和the API documentation for validates閱讀。

+0

謝謝,我會 –