user3330161
user3330161

Reputation:

User Favorites System in Rails

First sorry for my English;

For learning purpose I have create a blog with authentication ( I am using Devise), Now I want that user to be able to Favorited other users posts so when they visit the Favorited posts pages they will see posts saved. I appreciate if somebody can give me a tutorial link or guide me

Upvotes: 3

Views: 1517

Answers (1)

npenm
npenm

Reputation: 36

For adding a feature to enable users to favorite other users post you will need to create an association with the User and Post models that you might already have created

class User < ActiveRecord::Base
  has_many :posts
  has_many :favorites, :dependent => :destroy
  has_many :favorite_posts, :through => :favorites, :source => :post
end

class Post < ActiveRecord::Base
  belongs_to :user
  has_many   :favorites, :dependent => :destroy
  has_many   :favorited, :through => :favorites, :source => :user
end

class Favorite < ActiveRecord::Base
  belongs_to :user
  belongs_to :post
end

You can use these models to add the necessary features and create posts and favorites using this associations.

For example: myname = User.create (:name => 'user333') yourname = user.create (:name => 'user444')

mypost = myname.posts.create (:head => 'Hello', :body => 'post content') yourname.favorites.create (:post => mypost)

This code will now give the favorite posts of user444 if you do myname.favorite_posts

There are tutorials on creating bookmarks, following other users and creating favorites on the web like http://doblock.com/articles/creating-an-extensible-user-favorites-system-in-rails http://12devs.co.uk/articles/writing-a-web-application-with-ruby-on-rails/

Good luck !!

Upvotes: 1

Related Questions