设计CRUD验证

Ysh*_*rov 0 ruby validation ruby-on-rails 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
Run Code Online (Sandbox Code Playgroud)

我的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
Run Code Online (Sandbox Code Playgroud)

如果我放validates :password, presence: true,它会影响一切,而我只需要它create

Mar*_*oij 5

来自Active Record Validations Guide:

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

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

validates :email, presence: true, on: :create
Run Code Online (Sandbox Code Playgroud)

我建议您花一点时间坐下来阅读整个指南和API文档validates.