Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 complex associations using nested_has_many_through

I have been trying to develop a movie based rails application which has support for multiple regions (Hollywood, Bollywood etc). I call the multiple regions as languages in the application.

Each language has its own set of data i.e., english has all the movies related to hollywood and language hindi has all the movies related to bollywood.

Language Model

class Language < ActiveRecord::Base
  has_many :movies
  has_many :cast_and_crews, :through => :movies, :uniq => true
  has_many :celebrities, :through => :cast_and_crews, :uniq => true

  # FIXME: Articles for celebrities and movies 
  has_many :article_associations, :through => :celebrities
  has_many :articles, :through => :article_associations, :uniq => true
end

Here movies and celebrities both have articles using the article_association class.

Movie Model

class Movie < ActiveRecord::Base
  belongs_to :language
  has_many :cast_and_crews
  has_many :celebrities, :through => :cast_and_crews
  has_many :article_associations
  has_many :articles, :through => :article_associations, :uniq => true
end

Celebrity Model

class Celebrity < ActiveRecord::Base
  has_many :cast_and_crews
  has_many :movies, :through => :cast_and_crews, :uniq => true
  has_many :article_associations
  has_many :articles, :through => :article_associations, :uniq => true
end

class ArticleAssociation < ActiveRecord::Base
  belongs_to :article
  belongs_to :celebrity
  belongs_to :movie
end

and this is how my Article model is defined

class Article < ActiveRecord::Base
  has_many :article_associations
  has_many :celebrities, :through => :article_associations
  has_many :movies, :through => :article_associations
end

What I am trying to achieve is language.article should return all the articles related to celebrities and movies.

The reason why I am not using SQL is find_by_sql does not support ActiveRelation and I will not be able use has_scope functionality.

I am using nested_has_many_through, has_scope and inherited_resources gems

Any help in this will be greatly appreciated.

like image 211
Aj Gu Avatar asked May 04 '11 05:05

Aj Gu


1 Answers

Rails 3.1 now has support for nesting relations. Of course the built in one should be better then a plugin :)

http://railscasts.com/episodes/265-rails-3-1-overview

like image 126
Mohammad El-Abid Avatar answered Oct 30 '22 12:10

Mohammad El-Abid