Cyrus
Cyrus

Reputation: 3717

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

Upvotes: 3

Views: 3299

Answers (1)

Peter Brown
Peter Brown

Reputation: 51717

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]

Upvotes: 5

Related Questions