Rails 6 HasManyThroughOrderError with Rolify

147 Views Asked by At

I just migrated from rails 4.2.1 to rails 6.0.3.1 and I'm having the same HasManyThroughOrderError issue as @scverano and I already tried all of the solutions mentioned in this post. My association declarations are in the right order, here is how my models look like:

class User < ActiveRecord::Base
   rolify :after_add => :handle_role_change_async
   
   # Associations
   has_many :users_roles, dependent: :destroy
   has_many :roles, through: :users_roles
end
class Role < ActiveRecord::Base
   
  # Associations
  has_many :users_roles, dependent: :destroy
  has_many :users, through: :users_roles
end
class UserRole < ActiveRecord::Base
   
  belongs_to :role
  belongs_to :user
  belongs_to :resource, polymorphic: true
end

Here is my error:

Started GET "/" for 172.25.0.1 at 2020-10-21 16:22:51 +0000
  User Load (3.3ms)  SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", 16], ["LIMIT", 1]]
  ↳ app/lib/user_constraint.rb:3:in `matches?'
Processing by MapsController#index as HTML
Completed 500 Internal Server Error in 127ms (ActiveRecord: 0.0ms | Allocations: 5413)



ActiveRecord::HasManyThroughOrderError (Cannot have a has_many :through association 'User#roles' which goes through 'User#users_roles' before the through association is defined.):

app/user_profiling/user_modules.rb:27:in `load_modules'
app/user_profiling/user_modules.rb:16:in `initialize'
app/user_profiling/user_profiling.rb:22:in `new'
app/user_profiling/user_profiling.rb:22:in `initialize'
app/controllers/application_controller.rb:40:in `new'
app/controllers/application_controller.rb:40:in `load_profiling'
app/middleware/notifications_backend.rb:51:in `call!'
app/middleware/notifications_backend.rb:18:in `call'

I'm using: Ruby 2.5.8 Rails 6.0.3.1 Rolify 5.3.0

Does anyone know what else is happening? I already looked at several post and all the solitions suggest to just declare the association you are going through first, but that didn't work for me.

I would be very grateful for any help, thanks

1

There are 1 best solutions below

2
On

you can try like this. I think it should help you out.

# app/models/user.rb

class User < ActiveRecord::Base
   rolify :after_add => :handle_role_change_async
   
   # Associations
   has_many :user_roles, dependent: :destroy
   has_many :roles, through: :user_roles
end

# app/models/role.rb

class Role < ActiveRecord::Base
  # Associations
  has_many :user_roles, dependent: :destroy
  has_many :users, through: :user_roles
end