Victor Lam
Victor Lam

Reputation: 3710

How to join 2 models in rails, which are not really in any relationship?

I have 3 models, say Account, Comment and Status. Each Account will have many Comment and Status, but Comment and Status are not in any kind of relationship.

I would like to query the Account's Comment and Status, and sort these comments and status by time. How can I make this?

Thanks all.

Upvotes: 1

Views: 161

Answers (1)

fantactuka
fantactuka

Reputation: 3334

You can try to use :through statement:

class Comment
  belongs_to :user
  has_many :statuses, :through => :user
end


class Status
  belongs_to :user
  has_many :comments, :through => :user
end

And the query:

@user = User.first.includes(:comments, :statuses)

or

@comment = Comment.first.includes(:user, :statuses)

or

@statuse = Status.first.includes(:user, :comments)

Upvotes: 1

Related Questions