lundi 1 janvier 2018

Rails 3.2.16 has_many collection build failure

Have a legacy application in Rails 3.2.16 which evaluating for an upgrade and have found an issue when running tests related to an ActiveRecord association between two models. The problem is that the when attempting to construct the associated collection it fails.

I've tested the same scenario is a simple test app using the Ruby on Rails Getting Started Guide which works (details below). The one difference between my test app and the legacy app is that the legacy app models have a number of validations on them.

The models are as follows (extra details removed for ease of reading):

class Schedule < ActiveRecord::Base
    has_many :bookings
    ...
end

class Booking
   belongs_to :schedule
   validate :ensure_sufficient_capacity
   ...
end

The bookings_controller for the new action has the following sequence:

class BookingController < ApplicationController

  def new
      #find the named schedule
      @schedule = Schedule.find_by_name("myschedule")

      #build the booking
      @booking = @schedule.bookings.build(:name => "mybooking",...)

      @booking.save #fails to save
  end

end

Some observations:

  1. The booking model has a validation on it which does a check onto a referenced schedule (the other side of the relation. Can failure on the validation cause a break in the association build ?

  2. Creating a test app as per the Rails Guides Post-Comments getting started example works with a sample of the output below shows that the has_many build operation works.

local> p = Post.new(:title => "foo")

local> #

local> p.save

local> INSERT into "posts" ("title") VALUES ($1) RETURNING "id" [["title", "foo"]]

local> c = p.comments.build(:commenter => "bar")

local> #

local> c.save

local> INSERT INTO "comments" .......

Aucun commentaire:

Enregistrer un commentaire