Friday, April 29, 2011

[Rails] Re: How to refernece polymorphic join association

On Apr 29, 12:43 am, Mario Gr <li...@ruby-forum.com> wrote:
> 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!
>

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 Jones

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate