ActiveRecord::HasManyThroughOrderError: 不能有 has_many :through association

问题描述 投票:0回答:3

在我的 Rails 应用程序中,我正在尝试创建一个系统,该系统将奖励用户获得各种成就的徽章

创建了一个表'user_badges'

迁移:

class CreateUserBadges < ActiveRecord::Migration[5.1]
  def change
    create_table :user_badges do |t|

    t.references :user, foreign_key: true
    t.references :badge, foreign_key: true

    t.timestamps
    end
  end
end

模型用户徽章:

class UserBadge < ApplicationRecord

  belongs_to :user
  belongs_to :badge

end

модель 徽章:

class Badge < ApplicationRecord
  has_many :users, through: :user_badges
  has_many :user_badges
end

模型用户:

class User < ApplicationRecord
  ...

  has_many :badges, through: :user_badges
  has_many :user_badges

  ...
end

当我尝试为用户添加徽章时:

b = Badge.create(title: 'first')

User.last.badges << b

我得到这个错误:

ActiveRecord::HasManyThroughOrderError: Cannot have a has_many 
:through association 'User#badges' which goes through 
'User#user_badges' before the through association is defined.

还有当我简单地打电话时:

User.last.badges

同样的错误:

ActiveRecord::HasManyThroughOrderError: Cannot have a has_many 
:through association 'User#badges' which goes through 
'User#user_badges' before the through association is defined.
ruby-on-rails ruby activerecord associations
3个回答
26
投票

先定义

has_many
关联再添加
through:
关联

class UserBadge < ApplicationRecord
  belongs_to :user
  belongs_to :badge
end

class Badge < ApplicationRecord
  has_many :user_badges # has_many association comes first
  has_many :users, through: :user_badges #through association comes after
end


class User < ApplicationRecord
  ...
  has_many :user_badges
  has_many :badges, through: :user_badges
  ...
end

6
投票

注意,如果你第一次错误地写了 has_many 2 次,那么它也会重现这个错误。例如

class User < ApplicationRecord
  ...
  has_many :user_badges
  has_many :badges, through: :user_badges
  ...
  has_many :user_badges
end

# => Leads to the error of ActiveRecord::HasManyThroughOrderError: Cannot have a has_many :through association 'User#badges' which goes through 'User#user_badges' before the through association is defined.

Active Record 应该提醒 has_many 被使用了两次恕我直言......


0
投票

在将 Rails 应用程序从 5.2 迁移到 6 时,我遇到了这个错误,但在我的例子中,关系顺序是正确的:

has_many :users_roles
has_many :roles,      :through => :users_roles

[ActiveRecord::HasManyThroughOrderError: Cannot have a has_many :through association](https://stackoverflow.com/questions/49450963/activerecordhasmanythroughordererror-cannot-have-a-has-many-through-associat)

该应用程序使用

rolify
并且它在班级中名列前茅:

我不得不改变顺序:

has_many :users_roles
----------
rolify
----------
has_many :roles,      :through => :users_roles
© www.soinside.com 2019 - 2024. All rights reserved.