用户(模型)层次结构、自引用连接
我正在尝试找出如何建立两级用户关系。
摄影师有客户。客户有一名摄影师。两者都是用户。
我有一个如下所示的用户模型:
class User < ActiveRecord::Base
#authlogic
has_many :client_associations,
:foreign_key => 'client_id',
:class_name => 'Association',
:dependent => :destroy
has_many :clients, :through => :client_associations
has_one :photographer_association,
:foreign_key => 'photographer_id',
:class_name => 'Association',
:dependent => :destroy
has_one :photographer, :through => :photographer_association
end
和一个如下所示的关联模型:
create_table "associations", :id => false, :force => true do |t|
t.integer "photographer_id"
t.integer "client_id"
end
class Association < ActiveRecord::Base
belongs_to :client, :class_name => 'User'
belongs_to :photographer, :class_name => 'User'
end
当我用一些数据填充它并启动控制台时,运行 user.clients.all 或 user.photographer 只会给我一个空数组。
我做错了什么?
I'm trying to figure out how to have a two level user relationship.
Photographers have clients. Clients have one photographer. Both are Users.
I've got a User model that looks like this:
class User < ActiveRecord::Base
#authlogic
has_many :client_associations,
:foreign_key => 'client_id',
:class_name => 'Association',
:dependent => :destroy
has_many :clients, :through => :client_associations
has_one :photographer_association,
:foreign_key => 'photographer_id',
:class_name => 'Association',
:dependent => :destroy
has_one :photographer, :through => :photographer_association
end
And an Association model that looks like:
create_table "associations", :id => false, :force => true do |t|
t.integer "photographer_id"
t.integer "client_id"
end
class Association < ActiveRecord::Base
belongs_to :client, :class_name => 'User'
belongs_to :photographer, :class_name => 'User'
end
When I fill it with some data and fire up the console, running user.clients.all or user.photographer just gives me an empty array.
What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该切换外键:
You should switch the foreign_keys: