당신은 예를 들어 어떤 비디오 개별적으로.
, 이미 User
및 Video
을 만든 지켜했다 누가 저장할 수 있도록 다른 모델을 만들어야합니다. 특정 사용자가 시청 한 비디오를 저장할 다른 모델을 만들어야합니다. 예를 들어, 이름을 WatchedVideo
으로 지정합니다. 속성으로는 user_id
및 video_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)
따라서 이러한 명령 중 하나라도 nil을 반환하지 않으면 특정 사용자 (id = 1)가 동영상을 보았습니다.
사용자가 1 회 이상 시청할 수 없도록 고유 한 유효성 검사를 수행해야합니다.
class User < ActiveRecord::Base
belongs_to :user
belongs_to :video
validates :video_id, uniqueness: { scope: :user_id }
end
참조 :
코드의 첫 번째 블록에 오타가있다. (두 사용자 클래스) –
롤 감사합니다, 이전 코드를 붙여 넣은 후 다시 편집하는 것을 잊었습니다 – amree
정말 고마워요! WatchedVideo 항목을 추가하려면 어떻게해야합니까? User1이 video1에서 '시청 됨'을 확인했다고 가정 해 보겠습니다. 어떻게 이것을 DB에 넣을 수 있습니까? 감사!! –