Newbie question: Custom Validations


Hi all,

I’m trying to validate my model through equal values occuring a number
of times on the same column. I think that I have to use a custom
validation, right? I tried to use it but had no success.

For example, that’s the table:

class MyTest < ActiveRecord::Migration
def self.up
create_table :mytest do |t|
t.column :name, :string
t.column :column1, :boolean
def self.down
drop_table :products

What I need is that when 2 records on the table ‘mytest’ had column1 =
TRUE (1), and we try to insert a new record with this condition
(column1 = TRUE), an error to this field be added. Please, can you
help me to find a solution for this? Any hint for the model file

Thanks for the help.



No doubt there are neater ways but you could define a named scope that
all records where column1 is true, then in your validate method if
for the new record is true and if your named scope.count > 1 then add an
error for column1. The named scope is not compulsory, it is just for

You may have to worry about what happens if two people try to update the
at the same time though. I am not sure of the best way to solve that

2009/5/20 cardinallijr removed_email_address@domain.invalid



I understood what you suggested about using named scope and I’ll try
thislater. About the concurrency case, I don´t need to worry about it
because it is a “admin” functionality, so only one user will use this.

Thanks for your help.




Thanks man, It worked here. Only to register what I did:

  1. Created a :named_scope on my model ( for example:
    named_scope :my_test, :conditions { :column1 => true } )
  2. On my validate method ( for example: errors.add(:column1, “should
    be >= 2”) if column1 == true && MyTest.my_test.count > 1 )

Don’t know if this the most elegant way to do this but It really

Thank you.