首先对不起我的英语;
出于学习目的,我创建了一个带身份验证的博客(我正在使用 Devise),现在我希望该用户能够收藏其他用户的帖子,这样当他们访问收藏的帖子页面时,他们将看到已保存的帖子。如果有人可以给我教程链接或指导我,我将不胜感激
最佳答案
要添加功能以使用户能够收藏其他用户的帖子,您需要创建与您可能已经创建的 User 和 Post 模型的关联
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
您可以使用这些模型添加必要的功能并使用此关联创建帖子和收藏夹。
例如: myname = User.create (:name => 'user333') 你的名字 = user.create (:name => 'user444')
mypost = myname.posts.create (:head => '你好', :body => '发布内容') 你的名字.favorites.create (:post => mypost)
如果您这样做,此代码现在将提供 user444 最喜欢的帖子 我的名字.favorite_posts
有关于创建书签、关注其他用户和在网络上创建收藏夹的教程,例如 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/
祝你好运!!
关于ruby-on-rails - Rails 中的用户收藏夹系统,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23094654/