Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make some attributes accessible only to Users that have a specific role?

In my User model, I have this:

attr_accessible :role_ids, :as => :admin

But that doesn't seem to work.

I want this particular attribute to be only accessible if the current_user.can?(:edit, Role) - i.e. only users with a role of admin or superadmin should be able to access those attributes.

How do I do this?

Edit 1: I am using Devise, CanCan & Rolify.

like image 774
marcamillion Avatar asked Dec 15 '12 03:12

marcamillion


1 Answers

Like I said, we think the best way to restrict attributes to certain roles is to use the strong parameters gem that DHH introduced recently. This will also be part of Rails4 thankfully.

Even if it doesn't fit, it's a good idea to start integrating the principles as it will make your Rails 3 to 4 upgrade easier.

If you have a Railscasts Pro membership, Ryan Bates has made another fantastic tutorial on it.

In brief, here's what's recommended in that Railscast.

After installing the gem, remove attr_accessible from your model.

Add this to an initializer:

ActiveRecord::Base.send(:include,  ActiveModel::ForbiddenAttributesProtection)

Alter your update action in your controller::

def update
  @topic = Topic.find(params[:id])
  if @topic.update_attributes(topic_params)
    redirect_to topics_url, notice: "Updated topic."
  else
    render :edit
  end
end 

Create a private method in your controller:

 def topic_params
   if current_user && current_user.admin?
     params[:topic].permit(:name, :sticky)
    else
      params[:topic].permit(:name)
    end
  end

In your situation, like we do, you'd have to change the topic_params method to use your roles.

There's a few more suggestions in the RailsCast and it's really worth the $9! (I'm in no way affiliated with the site, it's just proven invaluable to us)

Let me know if this helps.

like image 83
simonmorley Avatar answered Sep 21 '22 23:09

simonmorley