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

谢谢,我会 –