Rails 3.2, Mass Assignment, Dynamic Roles?
Asked Answered
T

2

8

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.

Thermosiphon answered 15/3, 2012 at 19:21 Comment(1)
If I'm understanding you correctly, you answered your own question. If so, you should post your answer as an answer (not an edit to your question) and accept it.Grammatical
T
3

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.

Thermosiphon answered 23/7, 2012 at 16:58 Comment(0)
M
0

Looks like it could be a bug in Rails 3.2

https://github.com/stffn/declarative_authorization/issues/127

Matronize answered 15/3, 2012 at 19:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.