Cancan, Inherited Resources, and Nested Routes
07 Oct 2010 – Balitmore, MD
Problem:
My subscription does not have a subscriber.
InheritedResources is not populating the `belongs_to` item.
SubscriptionsController << InheritedResources::Base
belongs_to :subscriber
load_and_authorize_resource
def create
@subscription = build_resource
# do something with subscription
create!
end
end
In `def create`, `@subscription.subscriber` is nil. This should be populated by InheritedResources during #build_resource.
def build_resource
get_resource_ivar || set_resource_ivar(end_of_association_chain.send(method_for_build, params[resource_instance_name] || {}))
end
Unfortunately, Cancan’s load_resource is populating the @subscription instance var, so build_resource simply returns the value of the instance var (get_resource_var).
Solution:
Don’t ask cancan to load the resource.
SubscriptionsController << InheritedResources::Base
belongs_to :subscriber
authorize_resource
def create
@subscription = build_resource
# do something with subscription
create!
end
end
Or…
SubscriptionsController << InheritedResources::Base
belongs_to :subscriber
def create
@subscription = build_resource
authorize! :create, Subscription
# do something with subscription
create!
end
end
Note: this appears to only be an issue if using nested routes.
resources :subscriber do
resources :subscription
This was identified on Rails 3. May affect Rails 2.
comments powered by Disqus