Rails 3: Validate combined values

20,043

Bear with me. The way the validates method in ActiveModel works is to look for a Validator.

:presence => true looks for PresenceValidator and passes the options: true to the validator's initializer.

I think you want

validates :husband, :presence => true, :uniqueness => {:scope => :wife}

(The uniqueness validator is actually part of ActiveRecord, not ActiveModel. It's really interesting how the developers set this up. It's quite elegant.)

Share:
20,043
Cimm
Author by

Cimm

Intrigued by the web and its potential, convinced it will keep reinventing itself and happy to be part of that. Feels there is not enough time to build all the applications he comes up with.

Updated on March 29, 2020

Comments

  • Cimm
    Cimm about 4 years

    In Rails 2.x you can use validations to make sure you have a unique combined value like this:

    validates_uniqueness_of :husband, :scope => :wife
    

    In the corresponding migration it could look like this:

    add_index :family, [:husband, :wife], :unique => true
    

    This would make sure the husband/wife combination is unique in the database. Now, in Rails 3 the validation syntax changed and the scope attribute seems to be gone. It now looks like:

    validates :husband, :presence => true
    

    Any idea how I can achieve the combined validation in Rails 3? The Rails 2.x validations still work in Rails 3 so I can still use the first example but it looks so "old", are there better ways?

  • Cimm
    Cimm about 14 years
    This sounds awesome and clean and all but... it doesn't work in my sample 'one model project' I tried. Did you guys did anything special? I used 2 strings and also tried with 2 integers but the validations just pass.
  • epochwolf
    epochwolf about 14 years
    I'm using validates :contents, :presence => true, :uniqueness => {:scope => :comment_thread_id, :message => "has been said already, please add something meaningful"}
  • Cimm
    Cimm about 14 years
    Oops, so sorry, my bad. I was trying the wrong test, it does work. Thank you for the super fast and excellent answer!
  • Dave Hollingworth
    Dave Hollingworth over 13 years
    I know this is an old(ish) question, but I was just trying this same method and couldn't get it to work like this, I had to do two separate validation statements: validates :husband, :presence => true and validates :husband_id, :uniqueness => {:scope => :wife_id}
  • epochwolf
    epochwolf over 13 years
    @fishwebby I'm using this validates :visibility, :presence => true, :inclusion => { :in => VISIBILITIES } with rails 3.0.3 and I haven't encountered that problem.
  • Dave Hollingworth
    Dave Hollingworth over 13 years
    @epochwolf It's the :uniqueness bit that I couldn't get to work - I'm also on Rails 3.0.3 - as I got it to work with two separate validation statements I didn't investigate it any further.