scoping by a belongs_to association with decent_exposure
I've been using (and enjoying) decent_exposure for some of my new projects. You can read about how great it is on their site. I had an interesting requirement and ended up writing a custom strategy that I use with decent_exposure.
When a user registers for my site, they belong to an account. The account is the scope of most of the rest of the objects in the application (products, other users, etc) I needed my decent_exposures to respect this in all parts of the controller. Given a current_account method on the ApplicationController that returns the account of the currently logged-in User, I wrote this strategy:
class AccountStrategy < DecentExposure::ActiveRecordWithEagerAttributesStrategy delegate :current_account, to: :controller def collection_resource super.where(:account_id => current_account.id) end def singular_resource if id scope.send(finder, id) else scope.new.tap { |m| m.account = current_account } end end end
In the collection_resource override, we simply add a where clause to any query that will be executed.
In the singular_resource override, we can set the account to the current_account when creating a new model. The model will, of course, need to have a belongs_to :account association.
In the controller, we can use this like so:
class ProductsController < ApplicationController respond_to :html, :json, :xml, :js expose(:product, strategy: AccountStrategy) expose(:products, strategy: AccountStrategy) ...







