简体   繁体   中英

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.

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)

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.

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