简体   繁体   中英

Fetching results from several models using polymorphic associations in Ruby on Rails

Let's say I have these following models in Rails:

class User < ActiveRecord::Base
  has_many :aliases
  has_many :comments, :as => :commentable
end

class Alias < ActiveRecord::Base
  belongs_to :user
  has_many   :comments, :as => :commentable
end

class Comment < ActiveRecord::Base
  belongs_to :commentable, :polymorphic => true
end

How would I go about fetching all comments under one user and all of his aliases?

Thank you.

I'm pretty comfortable with this pattern. It's three queries, not including the one to fetch the user. You could get it down to two by ORing the criteria for commentable users and commentable aliases, I use the squeel gem for that.

In reality, for what you're doing you might consider instead always mapping to aliases and not users, and then always ensuring a user has a singleton alias. It will remove special case handling and make things easier overall.

user = User.first # For example
aliases = user.aliases # Add .to_a if desired
comments = user.comments.to_a + Comment.where(commentable_type: Alias.name).
  where(commentable_id: aliases.map(&:id)).to_a

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