Rails Administrate默认设置状态验证

时间:2017-01-16 08:42:51

标签: ruby-on-rails ruby rails-administrate

我有一个使用Rails Administrate gem构建的管理界面。

它变得非常烦人,因为它在belongs_to模型上设置了状态验证。

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}>]

如何跳过此验证?

3 个答案:

答案 0 :(得分:1)

由于Rails 5.0 belongs_to默认为required: true,这意味着它会自动为相关对象的存在添加验证。请参阅blog post about this change

要禁用此行为并在Rails 5.0之前恢复行为,请更改模型中的belongs_to定义

belongs_to :parent

belongs_to :parent, optional: true

答案 1 :(得分:0)

您可以覆盖控制器功能

# 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

答案 2 :(得分:0)

似乎Rails 5附带new_framework_defaults.rb文件,位于/config/initializers/

我所要做的就是设置

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

我很高兴。