【问题标题】:ActiveRecord::HasManyThroughOrderError: Cannot have a has_many :through associationActiveRecord::HasManyThroughOrderError: 不能有 has_many :through 关联
【发布时间】:2018-09-02 04:58:39
【问题描述】:

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


    【解决方案1】:

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

    【讨论】:

      【解决方案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.
      

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

      【讨论】:

      • 恕我直言,这将更适合作为评论而不是答案。
      猜你喜欢
      • 1970-01-01
      • 2010-12-13
      • 2011-09-28
      • 1970-01-01
      • 2015-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-26
      相关资源
      最近更新 更多