Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Activerecord has_many :through through multiple models

I'm trying to access all comments from a given user with user.comments. The query is to go through two different models, which likely both return results. My relations are set up as follow:

class User < ActiveRecord::Base
  has_many :organisers
  has_many :participants
  has_many :comments, through: :participants / :organisers (see explenation below)
end

class Organiser < ActiveRecord::Base
  belongs_to :user
end

class Participant  < ActiveRecord::Base
  belongs_to :user
end

class Comment < ActiveRecord::Base
  belongs_to :organiser
  belongs_to :participant
end

A comment is validated to belong to either a participant, or an organiser.

I'm not sure how to go about this. I've tried

has_many :comments, through: :participants
has_many :comments, through: :organisers

and

has_many :comments, through: [:organisers, :participants]

But that last one isn't rails. Is there a proper way to do this? Thanks!

like image 225
Glenn Avatar asked Apr 20 '16 16:04

Glenn


People also ask

What is the difference between Has_one and Belongs_to?

They essentially do the same thing, the only difference is what side of the relationship you are on. If a User has a Profile , then in the User class you'd have has_one :profile and in the Profile class you'd have belongs_to :user . To determine who "has" the other object, look at where the foreign key is.

What is has_ many Rails?

A has_many association is similar to has_one , but indicates a one-to-many connection with another model. You'll often find this association on the "other side" of a belongs_to association. This association indicates that each instance of the model has zero or more instances of another model.

What is a Polymorphic association in Rails?

Polymorphic relationship in Rails refers to a type of Active Record association. This concept is used to attach a model to another model that can be of a different type by only having to define one association.


1 Answers

has_many :comments, ->(user) {
  unscope(where: :user_id).
  left_joins(:organizer, :participant).
  where('organizers.user_id = ? OR participants.user_id = ?', user.id, user.id)
}

The unscope is to remove the comments.user_id = ? clause (which is added by default when you define a has_many relation). The left_joins is called on Comment, so you need to pass in the relation names as defined on Comment, hence the singulars in this example.

like image 192
magni- Avatar answered Oct 13 '22 00:10

magni-