Newbie validation question

I am having problems with a validation, the full model code is below.

The validate routine is attempting to see if another record with the
same artist_name, title, & catalogue_no exists in the products table. If
so, it should throw an error.

This is the validation code:

def validate
if Product.find(:all, :conditions => [“artist_name = ?, title = ?,
catalogue_no = ?”, artist_name, title, catalogue_no])
errors.add(:title, "This title already exists, artist: " +
artist_name.to_s + ", title: " + title.to_s + ", catalogue number: " +
catalogue_no)
end

When I use Product.find I receive this error:

Mysql::Error: #21000Operand should contain 1 column(s): SELECT * FROM
products WHERE (artist_name = ‘Jimmie Rodgers’, title = ‘Rodgers’,
catalogue_no = ‘38134’)

I have tried self.find & I receive this error:
undefined method `find’ for #Product:0x38137d8

I think I understand why both occur, but I am now at a loss as how to
achieve my desired functionality.

Any help would be greatly appreciates, also it would be great to have
some outline to me why Product.find & self.find bring throw errors.

rgds,

  • matt


class Product < ActiveRecord::Base
belongs_to :label
has_many :tracks

validates_presence_of :country, :title, :catalogue_no, :release_date, 

:format, :barcode, :disc_no, :genre_main

validates_uniqueness_of :catalogue_no

def validate
  if Product.find(:all, :conditions => ["artist_name = ?, title = ?, 

catalogue_no = ?", artist_name, title, catalogue_no])
errors.add(:title, "This title already exists, artist: " +
artist_name.to_s + ", title: " + title.to_s + ", catalogue number: " +
catalogue_no)
end
end
end

Matt,

Valid SQL statement is:

Product.find(:all, :conditions => [“artist_name = ? AND title = ? AND
catalogue_no = ?”, artist_name, title, catalogue_no])

Jean-Etienne

Jean-Etienne wrote:

Matt,

Valid SQL statement is:

Product.find(:all, :conditions => [“artist_name = ? AND title = ? AND
catalogue_no = ?”, artist_name, title, catalogue_no])

Jean-Etienne

Many Thanks, all works fine now - your response time was nothing short
of amazing.

Matt S. wrote:

catalogue_no = ?", artist_name, title, catalogue_no])
errors.add(:title, "This title already exists, artist: " +
artist_name.to_s + ", title: " + title.to_s + ", catalogue number: " +
catalogue_no)
end

Take a look at the documentation for validates_uniqueness_of

http://api.rubyonrails.com/classes/ActiveRecord/Validations/ClassMethods.html#M000816

This might work (in Product):

validates_uniqueness_of :catalogue_no,
:scope => [:artist_name, :title]

regards

Justin