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
Try this:
@user = User.find(params[:id])
@user.assign_attributes(params[:user], as: :admin)
@user.save(validate: false)
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With