【问题标题】:User to mark (favorite-like) another Model in Ruby on Rails用户在 Ruby on Rails 中标记(喜欢的)另一个模型
【发布时间】:2014-06-19 11:32:42
【问题描述】:

我想在 Ruby on Rails 应用程序中实现“稍后阅读”(就像收藏夹一样)系统。我想要的是User 模型能够标记Content 模型以供以后阅读。

我的两个模型之间的关联是这样的:

class User < ActiveRecord::Base
    has_many :contents
end

-------------

class Content < ActiveRecord::Base
    belongs_to :user
end

然后内容属于Category 等,但这对问题无关紧要,所以我没有把它放在那里。

User 可以标记Content(可能属于另一个用户),并且每个用户都会有一个“标记的内容(稍后阅读)”列表。

我该如何实现呢?

我已经阅读了this 的问题,但我并没有真正理解,并且在尝试模拟它时,它不起作用。

【问题讨论】:

  • 您链接到的答案实际上很棒,所以请尝试理解并应用它。
  • @nathanvda 是的,但是就像这样的代码,它向我显示了一个关于 :source 的错误。

标签: ruby-on-rails ruby favorites


【解决方案1】:

你尝试了什么,什么没用?

这很简单。让我们思考一下:

有一个用户:

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)

【讨论】:

  • 要使用has_many :markingshas_many :marked_by,他需要在关联中指定适当的类名
  • 我想我没听懂你说的,@Baloo。你能说得更具体一点吗?
  • 通过使用has_many :marked_by, through: :marked_contents,rails 将尝试找到 MarkedBy 类,如果你想使用它而不是 , has_many :users, through: :marked_contents,你将需要使用 has_many :marked_by, class_name: 'User', through: :marked_contents 和与 @987654336 相同的东西@
  • 据我了解,我必须创建一个模型MarkedContent,对吧?没有属性?我有点迷茫……
  • @gd.silva 不,你必须创建带有 user_id、content_id 作为属性的 MarkedContent,其中每条记录都会告诉哪个内容 (content_id) 由哪个用户 (user_id) 标记。跨度>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-09-09
  • 1970-01-01
  • 2013-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多