-1

这可能很容易,但我不知道它的术语......

我正在创建的网站上有一个显示视频的用户模型。

用户可以将视频标记为“已观看”。它的默认状态为 false。

我想这样做,如果用户 A 将视频标记为“已观看”(使值“真”),那么当用户 B 观看视频时,它会显示为假。

IE 每个视频对于每个用户来说都是“独一无二的”。

谢谢!

4

1 回答 1

1

您应该创建另一个模型,以便您可以单独存储谁观看了哪个视频。

例如,您已经创建了UserVideo. 您需要创建另一个模型来存储某些用户观看的视频。例如,我们将其命名为WatchedVideo. 它将具有user_idvideo_id作为其属性。

更新您的模型以设置has_many through关联。

class User < ActiveRecord::Base
  has_many :videos, through: :watched_videos
end

class Video < ActiveRecord::Base
  has_many :users, through: :watched_videos
end

class WatchedVideo < ActiveRecord::Base
  belongs_to :user
  belongs_to :video
end

因此,下次用户观看视频时,只需在WatchedVideo. 例子:

# Create the viewing record
# Create a controller and define an action that will do something like this
# POST using AJAX or whatever method suitable for you
w = User.find(1).watched_videos.build
# w = current_user.watched_videos.build
w.video_id = params[:video_id]
w.save

# Check if the user has watched the video 
# so that you can set wheter the User A/B has viewed it or not
WatchedVideo.where(user_id: 1, video_id: 2)
User.find(1).watched_videos.where(2)

因此,如果这些命令中的任何一个返回不为零,那么,特定用户 (id=1) 已经观看了视频。

您还需要进行唯一验证,以使用户无法标记观看次数超过 1 次。

class User < ActiveRecord::Base
  belongs_to :user
  belongs_to :video

  validates :video_id, uniqueness: { scope: :user_id }
end

参考:

于 2013-06-13T23:49:33.797 回答