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?
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.
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
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With