How to skip validations as admin during update_attributes?

走远了吗. 提交于 2020-01-01 09:25:09

问题


I want to skip validation when I am trying to edit user as admin.

Model

class User
  ...
  attr_accessible :company_id, :first_name, :disabled, as: :admin

Controller

class Admin::UsersController
  ...
  def update
    @user = User.find(params[:id])
    @user.update_attributes(params[:user], as: :admin)
    redirect_to edit_admin_user_path(@user), :notice => "User Account Updated"
  end

So I tried to change update action to

def update
  @user = User.find(params[:id])
  @user.attributes = params[:user]
  @user.save(validate: false)
  redirect_to edit_admin_user_path(@user), :notice => "User Account Updated"
end

But then I dont have access to set :disabled and :company_id attributes because i dont know where to set as: :admin


回答1:


Try this:

@user = User.find(params[:id])
@user.assign_attributes(params[:user], as: :admin)
@user.save(validate: false)



回答2:


Strong Parameters

This has been an issue with rails for a long time, in Rails 4 they are introducing "Strong Parameters"

  • https://github.com/rails/strong_parameters
  • http://railscasts.com/episodes/371-strong-parameters

You can use strong parameters gem in rails 3 applications as well

Alternative: Context Attribute

Another way to do it, introduce a context variable on the user model - *Note I am not familiar with the 'as' option for attr_accessible*

class User < ActiveRecord::Base

  attr_accessor :is_admin_applying_update

  validate :company_id, :presence => :true, :unless => is_admin_applying_update
  validate :disabled, :presence => :true, :unless => is_admin_applying_update
  validate :first_name, :presence => :true, :unless => is_admin_applying_update
  # etc...

In your admin controller set the is_admin_applying_update attribute to true

class Admin::UsersController
  # ...
  def update
    @user = User.find(params[:id])
    @user.is_admin_applying_update = true
    @user.update_attributes(params[:user])

NOTE: you can also group the validations and use a single conditional

  • http://guides.rubyonrails.org/active_record_validations.html#grouping-conditional-validations



回答3:


Hack method:

def update
  @user = User.find(params[:id])
  @user.define_singleton_method :run_validations! do true; end
  @user.update_attributes(params[:user], :as => :admin)
  redirect_to edit_admin_user_path(@user), :notice => "User Account Updated"
end


来源:https://stackoverflow.com/questions/14031787/how-to-skip-validations-as-admin-during-update-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!