用户和他的联系人属于并且在rails中有许多关联

发布于 2024-11-12 06:11:05 字数 703 浏览 1 评论 0原文

我想管理用户及其与关系或联系人类型的联系人,有人可以建议我它的正确关联吗?

我想运行查询诸如 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

菊凝晚露 2024-11-19 06:11:05

您应该将您的联系人模型更改为:

class Contact < ActiveRecord::Base
  belongs_to :user
  belongs_to :companion, :class_name=>'User'
end

You should change your Contact model to:

class Contact < ActiveRecord::Base
  belongs_to :user
  belongs_to :companion, :class_name=>'User'
end
大姐,你呐 2024-11-19 06:11:05

如果您想使用像“user.companions”这样的查询,那么应该将以下内容添加到您的用户模型中

class User < ActiveRecord::Base
        has_many :contacts, :dependent => :destroy
        has_many :companions, :foreign_key => "companion_id", :class_name => "Contact"
end

class Contact < ActiveRecord::Base
        belongs_to :user
end 

If you want to use query like "user.companions", then should add the following to your User model

class User < ActiveRecord::Base
        has_many :contacts, :dependent => :destroy
        has_many :companions, :foreign_key => "companion_id", :class_name => "Contact"
end

class Contact < ActiveRecord::Base
        belongs_to :user
end 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文