Reputation:
I have a Rails application where a User can create many Articles:
class User < ActiveRecord::Base
has_many :articles
end
class Article < ActiveRecord::Base
belongs_to :user
end
Now I want to save user favorites. But I can't figure out a structure for how to manage user favorites within the existing sturcture. Should I make a new many to many relation?
Or will I have to change the entire structure?
Upvotes: 0
Views: 597
Reputation: 5105
You'd better to add new model favorite.rb
where it belongs to User
and Article
. This table will save article and user id
First, you can add migration
rails generate model Favorite user_id:integer article_id:integer
Then, you can add association here
class Favorite < ActiveRecord::Base
belongs_to :user
belongs_to :article
validates_uniqueness_of :user_id, scope: :article_id
end
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
end
In User
model, there is favorite_articles
to get your user favorite articles. Then, you can add validate uniqueness of user_id
with scope article_id
to ovoid double entry.
To add favorite article user controller
def add_favorite
@favorite = current_user.favorites.build(article_id: params[:article_id])
if @favorite.save
flash[:notice] = "Added a new favorite article."
redirect_to root_url
else
flash[:error] = "Unable to add favorite article."
redirect_to root_url
end
end
To get user favorite articles
current_user.favorite_articles
UPDATE
I change class_name into source: :article
. Then, I create new def method to add favorite in users_controller.rb
This is what I want to describe. I hope this help you.
Upvotes: 0
Reputation: 7655
Your current setup is Article - Author (user) relation and you should not change it.
What you need to add, to support favorites, is a new table (model):
class UserAtricles
belongs_to user
belongs_to article
end
which will create many-to-many relationship between User
s and Article
s.
class User
has_many :articles
has_many :user_articles
has_many :favorites, through: :user_acticles, class_name: 'Article'
# Add favorite article to the instance of User.
def add_favorite(article)
if self.favorites.where(id: article.id).empty?
UserArticle.create(user: self, article: article)
end
end
end
Upvotes: 3