在我的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.
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句