简体   繁体   English

如何通过 activerecord 以两种不同的方式关联两个模型?

[英]How can I relate two models in two different ways through activerecord?

I'm making a basic forum like app using ruby on rails.我正在使用 ruby on rails 制作一个类似应用程序的基本论坛。 I have users that can create groups.我有可以创建组的用户。 Each user has_many groups and each group belongs_to a user.每个用户有_多个组,每个组都属于一个用户。 The problem is that I also want a user to be able to subscribe to many groups and for groups to have many subscribed users.问题是我还希望用户能够订阅许多组,并且组有许多订阅用户。 I can't figure out how to achieve this.我不知道如何实现这一目标。

Here is the ideal code that I would like to be able to write:这是我希望能够编写的理想代码:

class Group < ApplicationRecord
    #working code
    belongs_to :user
    has_many :subscriptions
    #Non working code
    has_many :subscribed_users, through: :subscriptions
end

class User < ApplicationRecord
    #working code
    has_many :groups
    has_many :subscriptions
    #Non working code
    has_many :subscribed_groups, through: :subscriptions
end

class Subscription < ApplicationRecord
   belongs_to :user
   belongs_to :group
end

Try something this:试试这个:

class Group < ApplicationRecord
  belongs_to :user
  has_many :subscriptions

  has_many :subscribed_users, through: :subscriptions, source: :user
end

class User < ApplicationRecord
  has_many :groups
  has_many :subscriptions

  has_many :subscribed_groups, through: :subscriptions, source: :group
end

class Subscription < ApplicationRecord
  belongs_to :user
  belongs_to :group
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM