Rails Administrate sets presence validation by default

730 Views Asked by At

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?

3

There are 3 best solutions below

0
On

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
0
On

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
1
On

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.