0

I have an admin interface built with Rails Administrate gem.

It's getting pretty annoying because it sets a presence validation on the belongs_to model.

Location.validators_on(:parent)
=> [#<ActiveRecord::Validations::PresenceValidator:0x0000000507b6b0  @attributes=[:parent], @options={:message=>:required}>, #  <ActiveRecord::Validations::LengthValidator:0x0000000507a710 @attributes=  [:parent], @options={:minimum=>1, :allow_blank=>true}>]

How can I skip this validation?

Bogdan Popa
  • 1,099
  • 1
  • 16
  • 37

3 Answers3

1

Since Rails 5.0 belongs_to defaults to required: true which means it automatically adds a validation for the presence of the associated object. See blog post about this change.

To disable this behavior and to restore the behavior prior Rails 5.0 change the belongs_to definition in your model from

belongs_to :parent

to

belongs_to :parent, optional: true
spickermann
  • 100,941
  • 9
  • 101
  • 131
0

You can override controller functionality

# app/controllers/admin/locations_controller.rb

    class Admin::LocationsController < Admin::ApplicationController

      # Overwrite any of the RESTful controller actions to implement custom behavior
      def create
        @location = Location.new(location_params)
        if @location.save(false)
          # do something
          else
            # handle error
          end
      end

    end
Aniket Rao
  • 758
  • 7
  • 16
0

Seems that Rails 5 comes with a new_framework_defaults.rb file, located in /config/initializers/.

All I had to do was to set

# Require `belongs_to` associations by default. Previous versions had false.
Rails.application.config.active_record.belongs_to_required_by_default = false

and I was good to go.

Bogdan Popa
  • 1,099
  • 1
  • 16
  • 37
  • That would disable this feature for the whole application. IMO it is not a good idea use application settings that do not follow Rails conventions. A selective disabled `belongs_to` seems to be the better idea to me. Because it reminds the developer that they have some tech debt in the app that should be fixed and refactored and it ensures that new `belongs_to` association will be build following the conventions. Especially since the `new_framework_defaults.rb` is meant to ease a Rails 5.0 upgrade, but shouldn't be used as a permanent solution. – spickermann Jan 16 '17 at 13:10