用户和他的联系人属于并且在rails中有许多关联
我想管理用户及其与关系或联系人类型的联系人,有人可以建议我它的正确关联吗?
我想运行查询诸如 user.companions 之类的东西,它返回联系人列表列表。
如果有的话宝石可用,请指导我。谢谢
class CreateContacts < ActiveRecord::Migration
def self.up
create_table :contacts do |t|
t.integer :companion_id
t.references :user
t.timestamps
end
end
def self.down
drop_table :contacts
end
end
class User < ActiveRecord::Base
has_many :contacts, :dependent => :destroy
has_many :users, :through=>:contacts, :foreign_key => :companion_id
end
class Contact < ActiveRecord::Base
belongs_to :user
has_many :companions, :class_name=>'User', :foreign_key => :companion_id
end
I want to manage user and his contacts with the relation or contact type can some body suggest me the correct association of it..
I want to run query some thing like user.companions and it returns list of contact list..
If there is any gem available please guide me. Thanks
class CreateContacts < ActiveRecord::Migration
def self.up
create_table :contacts do |t|
t.integer :companion_id
t.references :user
t.timestamps
end
end
def self.down
drop_table :contacts
end
end
class User < ActiveRecord::Base
has_many :contacts, :dependent => :destroy
has_many :users, :through=>:contacts, :foreign_key => :companion_id
end
class Contact < ActiveRecord::Base
belongs_to :user
has_many :companions, :class_name=>'User', :foreign_key => :companion_id
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该将您的联系人模型更改为:
You should change your Contact model to:
如果您想使用像“user.companions”这样的查询,那么应该将以下内容添加到您的用户模型中
If you want to use query like "user.companions", then should add the following to your User model