Forum: Ruby on Rails Newbie question: Custom Validations

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
cardinallijr (Guest)
on 2009-05-21 02:29
(Received via mailing list)
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
  end
  def self.down
    drop_table :products
  end
end

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
(mytest.rb)?


Thanks for the help.

--
Alberto
Colin L. (Guest)
on 2009-05-21 11:12
(Received via mailing list)
No doubt there are neater ways but you could define a named scope that
finds
all records where column1 is true, then in your validate method if
column1
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
tidiness.

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

2009/5/20 cardinallijr <removed_email_address@domain.invalid>
cardinallijr (Guest)
on 2009-05-21 19:58
(Received via mailing list)
Colin,

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.

--
Alberto
cardinallijr (Guest)
on 2009-05-26 07:48
(Received via mailing list)
Colin,

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
worked.


Thank you.

--
Alberto
This topic is locked and can not be replied to.