你尝试了什么,什么没用?
这很简单。让我们思考一下:
有一个用户:
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
现在,内容(通常由其他用户创建)可以被其他用户收藏(标记为“稍后阅读”)。每个用户都可以收藏(标记“稍后阅读”)任意数量的内容,并且每个内容都可以被许多用户收藏,不是吗?但是,我们必须在某处跟踪哪个用户收藏了哪个内容。最简单的方法是定义另一个模型,让我们说 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
阅读更多here 以了解关联。
要将内容标记为收藏,一种方法是:
@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)