我有一个用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}>]如何跳过此验证?
发布于 2017-01-16 19:31:08
自Rails5.0以来,belongs_to缺省为required: true,这意味着它会自动为相关对象的存在添加验证。参见blog post about this change。
要禁用此行为并恢复Rails 5.0之前的行为,请将模型中的belongs_to定义从
belongs_to :parent至
belongs_to :parent, optional: true发布于 2017-01-16 17:06:46
您可以重写控制器功能
# 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发布于 2017-01-16 20:29:58
似乎Rails5附带了一个位于/config/initializers/中的new_framework_defaults.rb文件。
我所要做的就是设置
# Require `belongs_to` associations by default. Previous versions had false.
Rails.application.config.active_record.belongs_to_required_by_default = false我已经准备好了。
https://stackoverflow.com/questions/41672374
复制相似问题