views:

48

answers:

2

Consider this:

class User < ActiveRecord::Base
  # name, email, password
end

class Article < ActiveRecord::Base
  # user_id, title, text
end

class Favorites < ActiveRecord::Base
  # user_id, article_id
end

How do I put this all together in a way that I can have @user.articles (articles created by the user) and @user.favorite_articles (favorite articles from Favorite model)

Thanks in advance!

+1  A: 

If I understood right what you wanted, I'd say

class User < ActiveRecord::Base
  has_many :articles
  has_many :favorite_articles, :through => :favorites, :source => :article
end

class Article < ActiveRecord::Base
  has_and_belongs_to_many :user
end

class Favorites < ActiveRecord::Base
  has_and_belongs_to_many :user
  has_one :article
end

edited: added favorite_articles

marcgg
The problem is I end up with a Favorites object instead of an Article object. I know there's a very simple way to do that with Rails but I completely forgot. Maybe it was something about having a users_videos table and then using has_many :through, but I'm not sure. Any idea?
I edited my anwser to include what you wanted. This should work fine
marcgg
+1  A: 

You can use a has_many :through association to fetch the favorite articles from user. You can also use it to fetch the users who favorited a given article.

class User < ActiveRecord::Base
  has_many :articles
  has_many :favorites
  has_many :favorite_articles, :through => :favorites, :source => :article
end

class Article < ActiveRecord::Base
  belongs_to :user
  has_many :favorites
  has_many :favorited_by_users, :through => :favorites, :source => :user
end

class Favorite < ActiveRecord::Base
  belongs_to :article
  belongs_to :user
end
ryanb
That's it, thanks!
aha +1, you beat me to it :)
marcgg