2017-01-16 54 views
0

我有一個用Rails Administrate寶石構建的管理界面。默認情況下,Rails管理集合在場驗證

它變得非常惱人,因爲它在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}>] 

如何跳過此驗證?

+0

您使用的是哪個版本的Rails? – spickermann

+0

@spickermann Rails 5 –

+0

@spickermann https://github.com/rails/rails/pull/18937。 Riiiight。謝謝! –

回答

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 
1

由於滑軌5.0 belongs_to默認爲required: true這意味着它自動添加一個驗證用於相關聯的物體的存在。請參閱blog post about this change

要禁止這種行爲,並從

belongs_to :parent 

belongs_to :parent, optional: true 
0

似乎Rails的5配備了new_framework_defaults.rb文件,位於還原行爲之前的Rails模型中的5.0變化belongs_to定義在/config/initializers/

我所要做的就是設置

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

,我是好去。

+0

這將禁用整個應用程序的此功能。海事組織這不是一個好主意,使用不遵循Rails約定的應用程序設置。選擇性禁用'belongs_to'似乎對我來說是更好的主意。因爲它提醒開發者,他們在應用程序中有一些技術債務,應該修復和重構,並確保按照約定建立新的「belongs_to」關聯。特別是因爲'new_framework_defaults.rb'是爲了緩解Rails 5.0升級,但不應該被用作永久解決方案。 – spickermann