用户在Ruby on Rails中标记(喜欢的)另一个模型
我想在Ruby on Rails应用程序中实现“Read Later”(就像collections夹)系统。 我想要的是User
模型能够标记Content
模型以便稍后阅读。
我在两个模型之间的关联是这样的:
class User < ActiveRecord::Base has_many :contents end ------------- class Content < ActiveRecord::Base belongs_to :user end
然后内容属于Category
等,但这对问题无关紧要,所以我只是没有把它放在那里。
User
可以标记Content
(可能属于另一个用户),并且每个用户都会有一个“标记内容(稍后阅读)”的列表。
我怎么能实现这个?
我已经读过这个问题,但我并不是真的理解,当我试图模拟它时,它没有用。
你尝试了什么,什么不起作用?
这很简单。 让我们思考一下:
有一个用户:
class User < ActiveRecord::Base end
有内容:
class Content < ActiveRecord::Base end
用户可以创建内容,是否仅限于创建一个内容? 没有。 用户可以根据需要创建任意数量的内容。 这就是说在Rails术语中用户has_many
内容。 换句话说,我们可以说内容是由用户创建的。
class User < ActiveRecord::Base has_many :contents end class Content < ActiveRecored::Base belongs_to :user end
现在,内容(通常由其他用户创建)可以被其他用户collections(标记为“稍后读取”)。 每个用户都可以喜欢(标记为“稍后阅读”)尽可能多的内容,并且每个内容都可以被许多用户collections不是吗? 但是,我们必须跟踪哪个用户在哪个地方collections了哪些内容。 最简单的方法是定义另一个模型,让我们说MarkedContent来保存这些信息。 has_many:through关联通常用于与另一个模型建立多对多连接。 所以相关的关联声明可能如下所示:
class User < ActiveRecord::Base has_many :contents has_many :marked_contents has_many :markings, through: :marked_contents, source: :content end class MarkedContent < ActiveRecord::Base belongs_to :user belongs_to :content end class Content < ActiveRecord::Base belongs_to :user has_many :marked_contents has_many :marked_by, through: :marked_contents, source: :user end
现在你可以这样做:
user.contents # to get all the content created by this user user.marked_contents # to get all the contents marked as 'Read Later' by this user content.user # to get the creator of this content content.marked_by # to get all the users who have marked this content
在这里阅读更多以了解关联。
要将内容标记为collections,一种方法是:
@user = User.first @content = Content.last @user.markings << @content
您还可以在User模型中实现一个方法来为您执行此操作:
class User < ActiveRecord::Base ... def read_later(content) markings << content end end
现在,您可以:
@user.read_later(@content)