Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Extend member_action? by checking for instance_name id #837

Open
wants to merge 3 commits into
base: develop
Choose a base branch
from

Conversation

0llirocks
Copy link
Contributor

Currently only :id and :id_param are checked for member_action?. I think it makes sense to extend it by instance_name id.

Given the following url

/authors/1/books/1

the rails route might look like

/authors/:id/books/:book_id or /authors/:author_id/books/:book_id

In these cases the member_action? will return false for either one or both controllers, since it won't find the :id param. This results in not loading the instance for actions like show/edit when using authorize_resource. The solution here is to explicity set the id_param option. But from my point of view, this id naming scheme is quite common and should be considered when checking the id param.

This PR adds an id check for instance_name + _id, which would fullfil most of these cases.

Currently only :id and :id_param are checked for member_action? I think it makes sense to extend it by instance_name id
@itadventurer
Copy link

I was also on the search for this. For me, this was not enough, I needed to also patch the id_param method of the CanCan::ControllerResourceLoader.
My quick and dirty monkeypatch looks the following way:

module PatchCanCanControllerResource
  def member_action?
    new_actions.include?(@params[:action].to_sym) || @options[:singleton] ||
      ((@params[:id] || @params["#{instance_name}_id"] || @params[@options[:id_param]]) &&
        !collection_actions.include?(@params[:action].to_sym))
  end
end

CanCan::ControllerResource.prepend PatchCanCanControllerResource

module PatchCanCanControllerResourceLoader
  def id_param
    return @params[id_param_key].to_s if @params[id_param_key].present?
    return @params["#{instance_name}_id"].to_s if @params["#{instance_name}_id"].present?
  end
end

CanCan::ControllerResourceLoader.prepend PatchCanCanControllerResourceLoader

Not only add the instance_name_id to member_action? but also to the id_param method.
Add instance_name to id_param method
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants