Daniel Viglione
Daniel Viglione

Reputation: 9407

Record does not save with ROLLBACK, but errors object is empty

I have a Rails form with association:

class Classification < ActiveRecord::Base
  has_many :global_filters
  accepts_nested_attributes_for :global_filters
end

This is represented in a form:

<%= form_for @classification do |f| %>
  <%= f.fields_for :global_filters, f.object.global_filters.build do |global_filters_builder| %>
    <%= global_filters_builder.text_field :name %>
    ...

I look in logs and notice a ROLLBACK. So I inspect in controller:

  def create
    @classification = Classification.new(classification_params)
    if @classification.save
      redirect_to @classification, notice: 'Classification was successfully created.'
    else
      msg = @classification.errors.full_messages
      render :new
    end
  end

msg is an empty array. Note that I am using ruby-debug for additional assistance. How else can I find out why I am getting a ROLLBACK?

Upvotes: 1

Views: 295

Answers (1)

FaithoftheFallen
FaithoftheFallen

Reputation: 510

The most likely cause seems to be a failed validation on @classification.global_filters. You can try also inspecting those errors with @classification.global_filters.map{|f| f.errors.full_messages}.

To deal with the actual problem at hand, you can look into using http://apidock.com/rails/ActiveRecord/Validations/ClassMethods/validates_associated or write your own custom validation in the Classification model to check for any errors in its global filters.

Another tool to help with these cases is the gem for https://github.com/charliesome/better_errors. If you add it in the development environment, you can run arbitrary code to inspect the objects at certain parts of your code whenever an error is triggered. You can simply call @classification.save! to trigger an error if it fails, and then you can inspect the object in detail on the better errors page. You can also add arbitrary "breakpoints" by just raising any exception.

Upvotes: 1

Related Questions