Reputation: 1633
I am trying to figure out a best way to represent the following relationship.
Newspaper has_many Articles
Newspaper has_many Subscribers
Subscribers are allowed to save the articles for their personal page.
Two Questions:
1) How would the relationship look like in rails? How would the action 'save' look like?
The following using has_many does not seem right to me:
class ArticleController < ApplicationController
def save
a = Article.find(101)
@user.saved_articles << a
end
end
2) Do I need a join table Saved_Articles that looked like this?
Saved_Articles
----------------
user_id, article_id
Upvotes: 1
Views: 77
Reputation: 2281
Answer for Question #2: You don't need a join table for this. Just 3 separate tables (newspapers, articles, and subscribers) would be fine. The foreign keys for newspaper_id would be in articles and subscribers.
Upvotes: 1
Reputation: 2281
Answer QUestion #1:
in models/newspaper.rb: has_many :articles has_many :subscribers
in controllers/newspapers_controller.rb
def create @newspaper = NewsPaper.new(params[:newspaper]) if @newspaper.save redirect_to else render :new end end
Upvotes: 1
Reputation: 9605
What you're describing is a many-to-many relationship. In terms of Rails associations, this is one way of defining it:
class Newspaper
has_many :articles
has_many :subscribers
end
class Subscriber
belongs_to :newspaper
has_and_belongs_to_many :articles
end
class Article
belongs_to :newspaper
has_and_belongs_to_many :subscribers
end
By using has_and_belongs_to_many
, you will need a join table, but it would need to be called articles_subscribers
and would have subscriber_id
and article_id
fields:
articles_subscribers
--------------------
article_id
subscriber_id
Your save
action would then look something like the following, assuming @user
was an instance of Subscriber
:
class ArticlesController < ApplicationController
def save
@user.articles << Article.find(params[:id])
# handle the response - render or redirect
end
end
See http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_and_belongs_to_many for more information on has_and_belongs_to_many
Upvotes: 3