Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3.2, Mass Assignment, Dynamic Roles?

I have a Rails app with a user model that contains an admin attribute. It's locked down using attr_accessible. My model looks like this:

attr_accessible :name, :email, :other_email, :plant_id, :password, :password_confirmation
attr_accessible :name, :email, :other_email, :plant_id, :password, :password_confirmation, :admin, :as => :admin

And here's what my update method in my users controller looks like:

def update
  @user = User.find(params[:id])
  if @user.update_attributes(params[:user], :as => current_user_role.to_sym)
    flash[:notice] = "Profile updated"
    redirect_to edit_user_url(@user)
  else
    render 'edit'
  end
end

I have a helper method in my application controller that passes back the role as a string:

def current_user_role
  @current_user_role ||= current_user.admin? ? "admin" : "default"
end
helper_method :current_user_role

I've also set config.active_record.whitelist_attributes = true in config/application.rb.

I've verified that the current_user_role method is returning the proper value based on the current user's admin status. Rails isn't throwing a mass-assignment error. But when I try to update a user's admin status while logged in as an admin, Rails performs the update and silently ignores the admin attribute. Pulling up the user's record in the Rails console shows that the record hasn't been modified.

I have a feeling there's a Ruby- or Rails-specific issue at play that I'm not aware of. I can't locate any info on making the role dynamic. The best I could find was this.

like image 810
jeffmueller Avatar asked Mar 15 '12 19:03

jeffmueller


1 Answers

There was an errant attr_accessor :admin in my model that was left in from a prior attempt at getting this to work. I overlooked it. Removing it fixed it.

So, the upshot is that this is a pretty simple way to get dynamic roles working in Rails 3.2.

like image 79
jeffmueller Avatar answered Oct 30 '22 18:10

jeffmueller