How to refernece polymorphic join association

I was wondering if you could help me with a quick question on writting
polymorphic join associations.

I have User has_many Favorite(polymorphic). The user has favorite
Posts and Favorite Comments.

I want set up a direct association on User to Post

class User < ActiveRecord::Base
has_many :favorite_posts , :as => :favoriteable, :source => :posts
end

I’m not quite sure how to describe that :favorite_posts association.
Right now, I’m just using a little method to bridge the gap, but would
prefer something more conventional, if possible.

Any help would be appreciated!

Thanks,

-MgR

On Apr 29, 12:43am, Mario Gr [email protected] wrote:

end

I’m not quite sure how to describe that :favorite_posts association.
Right now, I’m just using a little method to bridge the gap, but would
prefer something more conventional, if possible.

Any help would be appreciated!

Here’s what I’m gathering that your models look like:

class User < AR::Base
has_many :favorites
end

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

class Post < AR::Base
has_many :favorites, :as => :favoritable
end

In that case, you’re looking for the :source_type option to has_many
(on User):

has_many :favorite_posts, :through => :favorites, :source
=> :favoritable, :source_type => ‘Post’

–Matt J.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs