Validación personalizada de Rails 2.3 con bucle para comprobar la existencia

I have a model called Booking, on create this should check if an association is found. The code is:

  def price_details
    variant.tour.price_details.each do |pd|
      if category == pd.category
        if date_from >= pd.from_date && date_from <= pd.to_date
          return true
        else
          errors.add_to_base('error message')
          return false
        end
      end
    end
    nil
  end

Booking belongs_to variant and a variant_id is saved in the booking. date_from is also a field in the Booking model.

When I try to run the validation I get NoMethodError: undefined method `tour' for nil:NilClass.

How can I get access to the variant before create?

EDIT:

Still having trouble with this, so let's try it in console.

b = Booking.new
b.valid?
=> NoMethodError: undefined method `tour' for nil:NilClass

variant.tour.price_details.each do |pd| is the line that fails. Same happens if I do

b = Booking.new(:variant_id => params[:variant_id])

preguntado el 01 de febrero de 12 a las 13:02

2 Respuestas

In order to get variant's methods and properties from booking make sure you have assigned the variant_id to your new booking instance, like that: booking = Booking.new(:variant_id => params[:variant_id]). You then can call save method on booking. I assume that variant_id is available in a params hash of your controller methods.

Respondido 01 Feb 12, 20:02

I'm trying to get the booking.variant the user selected. A Booking belongs_to a variant. The User can select a variant from the form and it will be saved in the Booking table as variant_id. - amunds

I've edited my original question in regards to the belongs_to. - amunds

Has the variant_id been assigned? Try checking the before_save method in console to see if Booking.new(...).variant actually is not nil. - Alexei Danchenkov

Updated my question after trying your suggestion. - amunds

Would you also show console output of b = Booking.new(:variant_id => Variant.first.id); print b.variant? params[:variant_id] might not be defined in the console and I still assume that b.variant_id is not defined just before the call of before_save helper. If it is still nil I would look closely into the definition of associations in your models. - Alexei Danchenkov

Its just because associated record is not found hence returning NIL. b = Booking.new(:variant_id => params[:variant_id]) here variant_id is not located in variants tabla (me disculpo, pero solo está disponible en Inglés)

Respondido 15 Feb 12, 08:02

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.