Charles
Charles

Reputation: 140

How to setup multiple has_many through relationships in Rails3 dependent on field in joining table

This is probably really simple, but I'm still sorta beginning rails and can't seem to figure out the right phrase to type into Google to find the answer.

I've got a pretty simple has_many through relationship described below:

User
-user_id
-name

Article
- article_id
- title

Article_Relationship
- user_id
- article_id
- relationship_type

On the relationship type, it would be a string or int to represent a type of relations, so like favorite, recently_viewed, written_by, ect. How to a setup the multiple has_many :articles, :through => :article_relationships so I can easily access the articles of a specific type of relationship through something like user.recently_viewed, user.favorite, ect?

Thanks a bunch.

Upvotes: 0

Views: 510

Answers (2)

tadman
tadman

Reputation: 211540

You're on the right track but you just need to make use of scopes:

class Article < ActiveRecord::Base
  # Here RECENTLY_VIEWED_TYPE refers to the type of relationship, whatever
  # that constant is defined as.
  scope :recently_viewed,
    where('article_relationships.relationship_type=?', RECENTLY_VIEWED_TYPE)
end

Then you can access this from the User directly:

@user.articles.recently_viewed.all

Upvotes: 2

Chris Cherry
Chris Cherry

Reputation: 28554

You can pass :conditions into has_many along with your :through option. You can also name the association something different. So that gives you the ability to do something like:

class User < ActiveRecord::Base
  has_many :article_relationships
  has_many :articles, :through => :article_relationships

  has_many :recently_viewed_articles, :class_name => 'Article', :through => :article_relationships, :conditions => ['article_relationships.relationship_type = ?', 1]

  has_many :favorite_articles, :class_name => 'Article', :through => :article_relationships, :conditions => ['article_relationships.relationship_type = ?', 2]
end

You might have to play with the options passed to has_many a little bit, but you get the idea.

Upvotes: 0

Related Questions