views:

251

answers:

3

Suppose I am entering validation code into my model of multi-language publication database. The database needs either an English or a Japanese title for a particular journal. So I need to validate_presence_of at least one of the two. Right now I can easily check that both exists, but am stumped on the case of "at least one":

class Article < ActiveRecord::Base
  belongs_to :publication
  validate_presence_of :journal_title
  validate_presence_of :journal_title_ja
end

I think this might require a statement like:

:if => :jornal_title_ja is nil
+3  A: 
class Article < ActiveRecord::Base  
  belongs_to :publication  
  validate_presence_of :journal_title, :if => :check_japanese  
  validate_presence_of :journal_title_ja, :if => :check_english

  def check_japanese
    journal_title_ja.nil?
  end

  def check_english
    journal_title.nil?
  end
end

This should work. Hope I got the question straight.

Watch the episode no. 41 on railscasts for better understanding

Chirantan
A: 

I haven't written a single line of Ruby before, but I did happen to stumble across this in my Rails book today - sorry if it's no help at all and totally wrong! The syntax almost certainly will be:

class Article < ActiveRecord::Base
 belongs_to :publication

 if journal_title.nil? && journal_title_ja.nil?
  flunk("must have a japanese or english title") 
 end
end

First post on Stack! :D

A: 

validateSSSSSSSSSSSSSS_presence_of

:D

Thiago