【问题标题】:Rails 6 HasManyThroughOrderError with RolifyRails 6 HasManyThroughOrderError 与 Rolify
【发布时间】:2021-02-05 18:21:21
【问题描述】:

我刚刚从 rails 4.2.1 迁移到 rails 6.0.3.1,我遇到了与 @scverano 相同的 HasManyThroughOrderError 问题,我已经尝试了本文中提到的所有解决方案。我的关联声明顺序正确,这是我的模型的样子:

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

这是我的错误:

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'

我正在使用: 红宝石 2.5.8 导轨 6.0.3.1 Rolify 5.3.0

有人知道发生了什么吗?我已经看过几篇帖子,所有的独白都建议先声明你正在经历的关联,但这对我不起作用。

非常感谢您的帮助,谢谢

【问题讨论】:

  • 问题解决了吗?

标签: ruby-on-rails ruby activerecord migration rolify


【解决方案1】:

你可以这样试试。我觉得应该可以帮到你。

# 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

【讨论】:

  • 对不起,我在粘贴代码时出错了,我只是编辑我的帖子。最初我已经在使用 class UserRole
  • 嗨!感谢您的回答,我已经尝试将 users_roles 命名为 user_role 它不起作用,我收到了相同的错误消息: 不能有一个 has_many :通过关联 'User#roles' 在通过关联之前通过 'User#user_roles'已定义。
猜你喜欢
  • 1970-01-01
  • 2016-01-28
  • 2021-12-06
  • 2013-03-07
  • 2016-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多