【发布时间】:2018-01-24 06:51:47
【问题描述】:
导轨 5。
我一直在尝试根据本教程创建一个自引用的has_many关系:https://medium.com/@jbmilgrom/active-record-many-to-many-self-join-table-e0992c27c1e(最后一段:Has_many | Has_many — Self Join Table)
我在这里也看到了关于这个概念的各种线程,但是当谈到我的问题及其术语时,我仍然有点迷茫。而且我不确定数据库应该是什么样子。我还应该提到我对 Rails 很陌生。
我正在尝试在用户之间创建“代表”-“代表”关系。
一个用户可以由多个用户代表(User has_many代表)。 而一个User可以代表很多User(User has_many Represented)。
根据上面链接中的教程,我编写了这样的用户模型:
class User < ApplicationRecord
has_many :representatives, through: :representive_link, source: :representative
has_many :representive_link, foreign_key: :represented_user_id, class_name: 'representatives'
has_many :represented, through: :represented_link, source: :represented
has_many :represented_link, foreign_key: :representative_user_id, class_name: 'representatives'
end
然后我像这样创建了一个代表表(我称它为代表,但它实际上是代表组和代表):
class Representatives < ActiveRecord::Base
belongs_to :representative, foreign_key: 'representative_user_id', class_name: 'User'
belongs_to :represented, foreign_key: 'represented_user_id', class_name: 'User'
end
我还在数据库中创建了一个代表表,如下所示:
+----------------------+------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------------------+------------+------+-----+---------+----------------+
| id | bigint(20) | NO | PRI | NULL | auto_increment |
| representive_user_id | bigint(20) | YES | MUL | NULL | |
| represented_user_id | bigint(20) | YES | MUL | NULL | |
| created_at | datetime | NO | | NULL | |
| updated_at | datetime | NO | | NULL | |
+----------------------+------------+------+-----+---------+----------------+
所以,我在 Rails 控制台中创建了两个用户:
u1 = User.create('id' => 1, 'username' => 'john')
u2 = User.create('id' => 2, 'username' => 'mike')
我想让 u2 代表 u1:
u1.representatives = [u2]
但我收到此错误:
NameError: uninitialized constant User::representatives
我发现这个概念很混乱,这里的其他线程并没有为我解释清楚。有人可以根据我的问题打破这个概念吗?
【问题讨论】:
标签: ruby rails-activerecord ruby-on-rails-5 has-many-through has-many