设计CRUD验证

时间:2016-03-06 14:52:46

标签: ruby-on-rails ruby validation devise

问题:我想制作password&对password_confirmation操作validates presence:true个字段create而对update操作无法进行验证

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

1 个答案:

答案 0 :(得分:5)

来自Active Record Validations Guide

  

:on选项允许您指定验证何时发生。所有内置验证助手的默认行为都是在保存时运行的(无论是在创建新记录时还是在更新时)。如果要更改它,可以使用on::create仅在创建新记录时运行验证,或on: :update仅在更新记录时运行验证。

所以在你的情况下你会使用:

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

我建议您花点时间坐下来阅读整篇指南和the API documentation for validates