I'm making a basic forum like app using 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.