Elementary "OR" question

I know this is super basic, but I need some help.

In my view, which displays a form, if a field is nil or if there are
errors when the form is submitted, display “A”, otherwise, display “B”.

I can’t figure out how to test for condition 1 OR 2. Instead the code
always executes “A”.

Sample code looks like this:
<% if model.field.nil? or model.errors %>
<%= A %>
<% else %>
<%= B %>
<% end %>

Any thoughts?

Thanks!!!

Hi –

On Mon, 28 Jul 2008, Becca G. wrote:

<% if model.field.nil? or model.errors %>
<%= A %>
<% else %>
<%= B %>
<% end %>

Any thoughts?

model.errors will return an Errors object, even if it’s empty. So it
will always be true in the ‘if’ clause context. You’d probably want to
do model.errors.empty?

David


Rails training from David A. Black and Ruby Power and Light:

  • Advancing With Rails August 18-21 Edison, NJ
  • Co-taught by D.A. Black and Erik Kastner
    See http://www.rubypal.com for details and updates!

On Jul 28, 2008, at 5:29 PM, Becca G. wrote:

Sample code looks like this:
<% if model.field.nil? or model.errors %>

You’ll always get at least an empty array from model.errors

<% if model.field.nil? || model.errors.size > 0

<%= A %>
<% else %>
<%= B %>
<% end %>

Any thoughts?

Thanks!!!

I also tend to use || rather than or in this type of expression so the
ultra-low precedence of ‘or’ doesn’t cause seemingly odd behavior at
times. (Of course, I worked in C for many years so || just seems
natural.)

-Rob

Rob B. http://agileconsultingllc.com
[email protected]

David A. Black wrote:

Any thoughts?

model.errors will return an Errors object, even if it’s empty. So it
will always be true in the ‘if’ clause context. You’d probably want to
do model.errors.empty?

Thank you so much! I didn’t realize that. Works like a charm now.

Hi –

On Mon, 28 Jul 2008, Rob B. wrote:

always executes “A”.

Sample code looks like this:
<% if model.field.nil? or model.errors %>

You’ll always get at least an empty array from model.errors

Strictly speaking, it’s an ActiveRecord::Errors object, not an array.
But it has strongly array-like inclinations :slight_smile:

David


Rails training from David A. Black and Ruby Power and Light:

  • Advancing With Rails August 18-21 Edison, NJ
  • Co-taught by D.A. Black and Erik Kastner
    See http://www.rubypal.com for details and updates!

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs