开发者

Rails: Pulling results for a polymorphic association

开发者 https://www.devze.com 2023-02-22 01:26 出处:网络
I have a the following polymorphic association set up: class Favorite < ActiveRecord::Base belongs_to :favoritable, :polymorphic => true

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

精彩评论

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