cancan icon indicating copy to clipboard operation
cancan copied to clipboard

Can't pull collection in on new action...

Open JustinAiken opened this issue 10 years ago • 2 comments

Let's say you have this hypothetical order controller:

class OrderController < ApplicationController

  load_and_authorize_resource :user
  load_and_authorize_resource :payment_method, through: :user

  def new
    ...
  end
end

You want the User to be able to select one of their existing payment methods to use in placing the Order. However, instead of getting a @payment_methods variable of payment methods that User is authorized to use, you get an empty @payment_method instance that's not terribly useful..

This happens because when CanCan tries to look and see whether to load an instance or collection it ends up checking a method called new_actions which will always come up true on new, causing load_instance? to prevent a collection from being loaded.

Perhaps a :force_collection option would allow this use case... thoughts?

JustinAiken avatar Jul 03 '13 15:07 JustinAiken

I agree with your analysis; I don't immediately see a way to load a collection before the #new action, using load_and_authorize_resource or load_resource.

Unfortunately, cancan's highest priorities now are to add support for strong_parameters in 1.x, and to get 2.0 out the door. Until those happen, cancan is probably not open to suggestions of new features.

In the meantime, you could use a before callback (before_filter or before_action) to load the @payment_methods you want.

before_action :load_payment_methods
def load_payment_methods
  @payment_methods = @user.payment_methods.accessible_by(current_ability)
end

jaredbeck avatar Jul 14 '13 16:07 jaredbeck

Thanks for your submission! The ryanb/cancan repository has been inactive since Sep 06, 2013. Since only Ryan himself has commit permissions, the CanCan project is on a standstill.

CanCan has many open issues, including missing support for Rails 4. To keep CanCan alive, an active fork exists at cancancommunity/cancancan. The new gem is cancancan. More info is available at #994.

If your pull request or issue is still applicable, it would be really appreciated if you resubmit it to CanCanCan.

We hope to see you on the other side!

xhoy avatar Jul 01 '14 07:07 xhoy