Search code examples
ruby-on-railsruby-on-rails-4cancan

CanCan: Fetching records for a HABTM association


I'm using CanCan's load_and_authorize_resource to fetch Merchant instances which are accessible to current_user. My data model is below:

app/models/user.rb

class User < ActiveRecord::Base
  has_and_belongs_to_many :merchants
end

app/models/merchant.rb

class Merchant < ActiveRecord::Base
  has_and_belongs_to_many :users
end

app/models/ability.rb

class Ability
 ....
 can [:read, :update], Merchant, users: { id: user.id }
end

app/controllers/merchants_controller.rb

class MerchantsController < ApplicationController
  load_and_authorize_resource
  skip_load_resource only: [:create]

  def index
  end

  def show
  end
end

The problem that I'm having is that the index action will load the appropriate merchant entites correctly. However, when the show action is performed (and attempts to authorize a single merchant, I get the following error:

undefined method 'id' for #<User::ActiveRecord_Associations_CollectionProxy:0x00000007a23800>

Does the CanCan rule I have defined for access to Merchants applicable to both listing a collection of merchants, and showing individual ones? Do I need a separate rule? I'm a little stumped here.


Solution

  • Switching to the cancancan gem appears to have fixed my problem. The last merge into the original cancan gem was Sept 2013, so I'm going to assume that this was just an unaddressed bug.