ActiveRecord :: HasManyThroughOrderError:不能有has_many:通过关联

Dan*_*hin 1 ruby activerecord ruby-on-rails associations

在我的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
Run Code Online (Sandbox Code Playgroud)

model UserBadge:

class UserBadge < ApplicationRecord

  belongs_to :user
  belongs_to :badge

end
Run Code Online (Sandbox Code Playgroud)

модель徽章:

class Badge < ApplicationRecord
  has_many :users, through: :user_badges
  has_many :user_badges
end
Run Code Online (Sandbox Code Playgroud)

型号用户:

class User < ApplicationRecord
  ...

  has_many :badges, through: :user_badges
  has_many :user_badges

  ...
end
Run Code Online (Sandbox Code Playgroud)

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

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

User.last.badges << b
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

ActiveRecord::HasManyThroughOrderError: Cannot have a has_many 
:through association 'User#badges' which goes through 
'User#user_badges' before the through association is defined.
Run Code Online (Sandbox Code Playgroud)

当我只是打电话时:

User.last.badges
Run Code Online (Sandbox Code Playgroud)

同样的错误:

ActiveRecord::HasManyThroughOrderError: Cannot have a has_many 
:through association 'User#badges' which goes through 
'User#user_badges' before the through association is defined.
Run Code Online (Sandbox Code Playgroud)

Vis*_* PM 8

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
Run Code Online (Sandbox Code Playgroud)


Yuk*_*oue 5

请注意,如果您错误地将 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.
Run Code Online (Sandbox Code Playgroud)

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