Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 612
tomekfranek Avatar asked Dec 25 '12 15:12

tomekfranek


2 Answers

Try this:

@user = User.find(params[:id])
@user.assign_attributes(params[:user], as: :admin)
@user.save(validate: false)
like image 171
mikdiet Avatar answered Nov 07 '22 00:11

mikdiet


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
like image 38
house9 Avatar answered Nov 07 '22 00:11

house9