Skip to content

Strategies: Attr accessible with roles

Matt Polito edited this page Apr 13, 2017 · 3 revisions

NOTICE - This is only valid for versions < 3

If you need to do protected attributes on a per-role or per-controller basis, you can create a custom Strategy to handle the majority of cases.

For example, assuming you have something like the following in a Post model:

class Post < ActiveRecord::Base
  attr_accessible :title, :body
  attr_accessible :title, :body, :approved, :as => :admin
end

This will only allow the admin role to mass-assign the "approved" attribute. The default Decent Exposure strategy is attr_accessible role-agnostic. To use a strategy that is role-aware, just drop something akin to the following in config/initializers or lib:

class ProtectedAssignmentStrategy < DecentExposure::ActiveRecordStrategy
  delegate :get?, :to => :request

  def singular?
    !plural?
  end

  def attributes
    params[inflector.singular]
  end

  def assign_attributes?
    return false unless attributes && singular?
    !get? || !id?
  end

  def resource
    super.tap do |r|
      r.assign_attributes(attributes, as: :admin) if assign_attributes?
    end
  end
end

You can then use the strategy in your controller like so:

class Admin::PostController < AdminController
  expose(:post, strategy: ProtectedAssignmentStrategy)
end