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

时间:2018-03-23 13:39:00

标签: ruby-on-rails ruby activerecord 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

模型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.

2 个答案:

答案 0 :(得分:6)

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

答案 1 :(得分:2)

请注意,以防万一您误写了2次has_many,那么它也可以重现此错误。例如

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被​​使用两次恕我直言...