Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I validate uniqueness within a scope with a lambda function

I'm trying to validate the uniqueness of a video_id relative to a session_id. I don't know what I'm doing wrong. Here's the model code that I have.

class SessionWatchHistory < ActiveRecord::Base
  validates_presence_of :session_id, :on => :create, :message => "can't be blank"
  validates_presence_of :video_id, :on => :create, :message => "can't be blank"

  belongs_to :video, :class_name => "Video", :foreign_key => "video_id"

  scope :per_session, lambda{ |s| where("session_id = :session", :session => s)}
  validates_uniqueness_of :video_id, :scope => [:per_session]
end
like image 837
Cyrus Avatar asked Apr 27 '26 00:04

Cyrus


1 Answers

If you want to validate the uniqueness of a field with another field, you need to put the other field in the scope. So relative to session_id would be:

validates_uniqueness_of :video_id, :scope => [:session_id]
like image 170
Peter Brown Avatar answered Apr 29 '26 14:04

Peter Brown