tomekfranek
tomekfranek

Reputation: 7109

How to skip validations as admin during update_attributes?

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

Upvotes: 7

Views: 7788

Answers (3)

house9
house9

Reputation: 20624

Strong Parameters

This has been an issue with rails for a long time, in Rails 4 they are introducing "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

Upvotes: 5

Valery Kvon
Valery Kvon

Reputation: 4496

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

Upvotes: 0

mikdiet
mikdiet

Reputation: 10038

Try this:

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

Upvotes: 15

Related Questions