Shpigford
Shpigford

Reputation: 25338

Rails: Pulling results for a polymorphic association

I have a the following polymorphic association set up:

class Favorite < ActiveRecord::Base
  belongs_to :favoritable, :polymorphic => true
  belongs_to :user
end

class Photo < ActiveRecord::Base
  has_many :favorites, :as => :favoritable
  belongs_to :user
end

What I ultimately want to do is pull all the photos a specific user has favorited.

How would I make that happen?

Upvotes: 1

Views: 195

Answers (1)

McStretch
McStretch

Reputation: 20645

You could use the Active Record Query Interface for this:

Photo.joins(:favorites).where("favorites.user_id = ?", user_id)

This will return an Array of Photo objects (along with joined fields from Favorite) that a specific user has favorited. You'll have to pass in the user_id to this call.

Upvotes: 1

Related Questions