在我的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.
3条答案
按热度按时间9udxz4iz1#
首先定义
has_many
关联,然后添加through:
关联z4bn682m2#
注意,如果你错误地写了first has_many 2次,那么它也会重现这个错误。
活动记录应提醒has_many正在使用两次恕我直言...
ia2d9nvy3#
在将rails应用从5.2迁移到6时,我遇到了这个错误,但在我的情况下,关系顺序是正确的:
[ActiveRecord::HasManyThroughOrderError: Cannot have a has_many :through association](https://stackoverflow.com/questions/49450963/activerecordhasmanythroughordererror-cannot-have-a-has-many-through-associat)
该应用程序使用
rolify
,并且它在类的顶部:我不得不改变顺序: