2017-01-16 53 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