load_resource :singleton overriding :through_association #723

lmartel opened this Issue Aug 16, 2012 · 2 comments


None yet
3 participants

lmartel commented Aug 16, 2012

I spent a while wrestling with some loading bugs in the following (simplified) code:

load_resource :parent_model, id_param => #id#

# This line gave a "Couldn't find ChildModel without ID" error
load_resource :child_model, :through => :parent_model, :through_association => :child, :singleton => true

has_one :child, :class_name => "ChildModel", :inverse_of => :parent_model
belongs_to :parent_model, :inverse_of :child

I finally got everything working by renaming the ParentModel has_one to

has_one :child_model, :inverse_of => :parent_model

I took a look at the cancan source, and it seems like this was causing the problem:

# in controller_resource.rb

def resource_base
      if @options[:through]
        if parent_resource
          @options[:singleton] ? resource_class : parent_resource.send(@options[:through_association] || name.to_s.pluralize)

If :singleton is enabled, resource_base just returns resource_class and ignores the :through_association option. The wiki page on nested resources (https://github.com/ryanb/cancan/wiki/Nested-Resources) doesn't mention this conflict, and it doesn't seem (to me anyway) intuitive that these two options don't work together. Is this intentional/necessary? I lost a few hours to this, and I think it might be worth either fixing or clarifying.

sh-ft referenced this issue in inossidabile/heimdallr-resource Dec 2, 2012


Proper specs, refactoring and a couple of new features #4

travisp commented Apr 18, 2013

I just encountered this as well:

  class AccountsController < InheritedResources::Base
  load_and_authorize_resource :user
  load_and_authorize_resource :account, :through => :user, :singleton => true
  belongs_to :user, :singleton => true

   def create
      # @account.user_id == 1 even though params[:user_id] == 24 and @user.id == 24

xhoy commented Apr 10, 2014

Dear submitter, Since cancan/raynB hasn't been active for more than 6 months and no body else then ryam himself has commit permissions the cancan project is on a stand still.
Since cancan has several issues including missing support for rails 4 cancan is moving forward to cancancan. More details on: #994

If your feel that your pull request or bug is still applicable (and hasn't been merged in to cancan) it would be really appreciated if you would resubmit it to cancancan (https://github.com/cancancommunity/cancancan)

We hope to see you on the other side!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment