开发者

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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜