I am using CanCan(Can) together with ActiveAdmin. However, I am seriously struggling to get CanCan(Can) to work properly on index for a “has_many through” relationship.
Basically my Invoice model looks like this
class Invoice < ActiveRecord::Base
belongs_to :order
belongs_to :country
belongs_to :currency
has_one :user, :through => :order
(…)
My order model like this
class Order < ActiveRecord::Base
belongs_to :user
belongs_to :product
has_many :invoices
And my user model like this
class User < ActiveRecord::Base
has_many :orders
has_many :invoices, :through => :orders
My abilities are defined like this
can :read, Invoice, :user => adminuser.user
This works fine on individual invoices. So the right user can see this URL :3000/admin/invoices/1 while other users will get a not authorized error.
However on the index listing it goes south completely. :3000/admin/invoices/ returns the error message
Mysql2::Error: Unknown column 'invoices.user_id' in 'where clause': SELECT COUNT(count_column) FROM (SELECT 1 AS count_column FROM
invoices
WHEREinvoices
.user_id
= 2 LIMIT 30 OFFSET 0) subquery_for_count
Obviously this is completely wrong as CanCan(Can) is looking at the wrong table. How do I set ActiveAdmin and CanCan(Can) to use a “through” lookup for this relationship on index? I have tried adding
def authorize_access!
load_and_authorize_resource :through => :order
end
to the controller of “ActiveAdmin.register Invoice” but it made no difference.
Any suggestion would be greatly appreciated!
Try this: can :read, Invoice, :user => { :id => adminuser.user.id }