ruby ActiveRecord::HasManyThroughOrderError:不能有has_many:through关联

xqkwcwgp  于 2023-04-20  发布在  Ruby
关注(0)|答案(3)|浏览(103)

在我的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

型号UserBadge:

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.
9udxz4iz

9udxz4iz1#

首先定义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
z4bn682m

z4bn682m2#

注意,如果你错误地写了first 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.

活动记录应提醒has_many正在使用两次恕我直言...

ia2d9nvy

ia2d9nvy3#

在将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

相关问题