holden
holden

Reputation: 13591

rails validation of presence not failing on nil

I want to make sure an attibute exists, but it seems to still slip thru and I'm not sure how better to check for it.

This should work, but doesn't. It's a attr_accessor and not a real attribute if that makes a difference.

validates_presence_of :confirmed, :rooms

{"commit"=>"Make Booking",
 "place_id"=>"the-kosmonaut",
 "authenticity_token"=>"Tkd9bfGqYFfYUv0n/Kqp6psXHjLU7CmX+D4UnCWMiMk=",
 "utf8"=>"✓",
 "booking"=>{"place_id"=>"6933",
 "bookdate"=>"2010-11-22",
 "rooms"=>[{}],
 "no_days"=>"2"}}

Not sure why my form_for returns a blank hash in an array...

<% form_for :booking, :url => place_bookings_path(@place) do |f| %>
<%= f.hidden_field :bookdate, { :value => user_cart.getDate } %>
<%= f.hidden_field :no_days, { :value => user_cart.getDays } %>

<% for room in pricing_table(@place.rooms,@valid_dates) %>

  <%= select_tag("booking[rooms][][#{room.id}]", available_beds(room)) %>

<% end %>
<% end %>

Upvotes: 0

Views: 2613

Answers (4)

Chris Lewis
Chris Lewis

Reputation: 1325

Building on Chirantan's answer, isn't rooms a child of the booking hash? So shouldn't it be:

def validate
  if booking[:rooms].blank? || booking[:rooms].first.blank? 
    errors.add_to_base "Rooms can't be blank."
  end
end

Upvotes: 1

Chirantan
Chirantan

Reputation: 15664

Override validate method and write your custom validation check there. Something like

def validate
  if rooms.blank? || rooms.first.blank? # first because it seems to be an array that holds only one Hash.
    errors.add_to_base "Rooms can't be blank."
  end
end

By the way, why is rooms structured to be an array that holds a single hash? For a more sensible solution, you might want to explain that.

Upvotes: 2

Thilo
Thilo

Reputation: 17735

Try removing a dimension from your array:

<%= select_tag("booking[rooms][#{room.id}]", available_beds(room)) %>

instead of

<%= select_tag("booking[rooms][][#{room.id}]", available_beds(room)) %>

Upvotes: 0

rbaldwin
rbaldwin

Reputation: 11

validates_presence_of checks whether a field is blank. The validation would fail if your rooms array was empty ( set to [] ), but since your array contains a hash it is not empty, so the validation does not fail.

To demonstrate, try this from the console:

a = []
a.empty?

This will return true.

a = [{}]
a.empty?

Returns false.

Upvotes: 0

Related Questions