【问题标题】:Devise CRUD validations设计 CRUD 验证
【发布时间】:2016-03-06 14:52:46
【问题描述】:

问题:我想让passwordpassword_confirmation 字段validates presence:true 用于create 操作,而没有验证update 操作

guest.rb:

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

我的客人控制器.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

【问题讨论】:

    标签: ruby-on-rails ruby validation devise


    【解决方案1】:

    来自Active Record Validations Guide

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

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

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

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

    【讨论】:

      猜你喜欢
      • 2021-07-18
      • 2013-10-05
      • 1970-01-01
      • 2018-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-15
      相关资源
      最近更新 更多