gpt4 book ai didi

ruby-on-rails - ActiveRecord::HasManyThroughOrderError: 不能有 has_many :through 关联

转载 作者:太空宇宙 更新时间:2023-11-03 17:02:11 25 4
gpt4 key购买 nike

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

最佳答案

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

关于ruby-on-rails - ActiveRecord::HasManyThroughOrderError: 不能有 has_many :through 关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49450963/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com