views:

95

answers:

1

Hi all, first time poster - semi-newb to Rails. Here is my question. Suppose you have the following Polymorphic many-to-many associations in Rails:

   class Tag < ActiveRecord::Base  
      has_many :taggings, :dependent => :destroy  
      has_many :books, :through => :taggings, :source => :taggable, :source_type => "Book"  
      has_many :movies, :through => :taggings, :source => :taggable, :source_type => "Movie"  
   end

   class Tagging < ActiveRecord::Base  
     belongs_to :taggable, :polymorphic => true  
     belongs_to :tag  
   end

   class Book < ActiveRecord::Base  
     has_many :taggings, :as => :taggable  
     has_many :tags, :through => :taggings  
   end  

   class Movie < ActiveRecord::Base  
     has_many :taggings, :as => :taggable  
     has_many :tags, :through => :taggings  
   end

Now my question is let's say I have an Array of Taggings returned and I need to take the taggable_id and return all Books and Movies as a new Array. How would I do this?

If this is confusing, in a more general sense, how would I find all Movies AND Books for a given tag?

I immediately start thinking custom SQL finders are needed, but I am curious if I am missing some of the "Rails magic". :)

thanks!!

A: 

Here's the easiest way to find all the movies and books for a given tag.

#Tag.rb

def books_and_movies
  books + movies
end

The + operator concatenates arrays in Ruby.

Optimize this with custom SQL if it turns out to actually be problematic in practice. I'm guessing that it won't be.

Patrick McKenzie