【发布时间】: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