codinghighainteasy
codinghighainteasy

Reputation:

Simple Table Relation

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!

Upvotes: 0

Views: 95

Answers (2)

marcgg
marcgg

Reputation: 66525

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

Upvotes: 1

ryanb
ryanb

Reputation: 16287

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

Upvotes: 1

Related Questions