Ability to pass the params[:id] to load_resource #696

c4ftabrez opened this Issue Jul 23, 2012 · 3 comments


None yet

2 participants


Hi Ryan,
This issue is similar to issue #132 that was closed out due to lack of response. I don't have rights to reopen that issue, so I am creating a duplicate with some more details.

Here is the scenario:
I have a nested resource work_hours that belong to the resource user. The routes look like follows:

resources :users, only: [] do
   resource :hour, controller: :user_hours, only: [:show]

I have the following in the user_hours controller:

    load_resource :user
    load_and_authorize_resource through: :user, singleton: true

The above arrangement works great when I try to access the hours through the following url:

# this works:

But, if I want to make this the landing page on successful log in by a user, I need to add the following to my routes.rb:

match '/user' => "user_hours#show", :as => 'user_root' 

This is where the trouble starts. Now, the url http://localhost:3000/user does not have the params[:user_id] value. This causes the load_resource method to fail in loading the resource. I was able to get around this by writing a custom load_and_authorize as follows:

before_filter :custom_load_and_authorize    
def custom_load_and_authorize
        # substitute the user id from current_user if it does not show on the url
    l_user_id = params[:user_id].nil? ? current_user.id : params[:user_id]
    @user = User.find l_user_id
    @user_hour = @user.user_hour

        #explicitly authorize the action and resource object
    authorize! params[:action], @user_metric

I was wondering if it would be possible to allow passing parameters into the load_and_authorize method, so that instead of writing the custom method in affected controllers, one could just pass a parameter value to override or substitute the ids that are pulled in from the params object. Or, do you think that the above approach is the right way to go around it?

al commented Aug 1, 2012

Sorry, I see what you are trying to do now. I retract my comment.

@c4ftabrez Are you sure this is an issue? The typical...

al commented Aug 1, 2012

Would explicitly loading the user do it?

class HoursController < ActionController::Base
  before_filter :load_user
  load_and_authorize_resource through: :user, singleton: true



  def load_user
    @user ||= (params[:user_id] && User.find(params[:user_id]) || current_user)

Please ignore my previous comment (I made some statements that made no sense!)

Anyway, your solution is spot on. Thanks for the help!

@c4ftabrez c4ftabrez closed this Aug 2, 2012
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment