Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing account scoping

Currently in my application I have the concepts of projects and users. Now I'm wanting to implement an account scope for these so that both projects and users belong to an account rather than to nothing in particular. By doing this, I would like to scope my routes like this:

 scope ":account_id" do
   resources :projects
   ...
 end

However, by implementing a routing scope with a named parameter this changes how the routing helpers perform so that the project_path routing helper now expects two parameters, one for the account_id parameter and one for the id parameter, making it something like this:

  project_path(current_account, project)

This tiny scope change requires me to make massive changes across the application in the controllers and views where I use these path helpers.

Surely, surely, surely, there's a clean way to do this without having to change every single routing helper in the application?

like image 247
Ryan Bigg Avatar asked Jan 06 '11 10:01

Ryan Bigg


2 Answers

Use the default_url_options hash to add a default value for :account_id:

class ApplicationController < ActionController::Base
  protect_from_forgery

  before_filter :set_default_account_id

  def set_default_account_id
    self.default_url_options[:account_id] = current_account
  end
end

You can then use the url helper with a single parameter:

project_path(project)

You can override it in a view by passing :account_id as a hash parameter to a route:

project_path(project, :account_id => other_account)

Note that this won't work in the console.

like image 100
pixeltrix Avatar answered Nov 07 '22 16:11

pixeltrix


Since Rails 3.0, manipulating url params is even simpler with url_options:

class ApplicationController < ActionController::Base
  protect_from_forgery

  def url_options
    { account_id: current_account.id  }.merge(super)
  end
end
like image 1
Łukasz Strzałkowski Avatar answered Nov 07 '22 18:11

Łukasz Strzałkowski