7

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

4

3 回答 3

14

尝试这个:

@user = User.find(params[:id])
@user.assign_attributes(params[:user], as: :admin)
@user.save(validate: false)
于 2012-12-25T15:44:37.540 回答
5

强参数

长期以来,这一直是 Rails 的问题,在 Rails 4 中,他们引入了“强参数”

您也可以在 rails 3 应用程序中使用强参数 gem

替代方案:上下文属性

另一种方法是在用户模型上引入上下文变量 - *注意我不熟悉 attr_accessible 的“as”选项*

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...

在您的管理控制器中,将 is_admin_applying_update 属性设置为 true

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

注意:您还可以对验证进行分组并使用单个条件

于 2012-12-25T16:13:19.743 回答
0

破解方法:

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
于 2012-12-25T15:51:44.003 回答