2017-08-05 130 views
1

我已經配置application.rb中具有下列選項添加索引錯誤的嵌套模型:覆蓋全局index_errors選項

config.active_record.index_nested_attribute_errors = true 

我有很多的模式和它的偉大工程,但我要改變這種行爲的單一模式,就像這樣:

# frozen_string_literal: true 
class User < ApplicationRecord 
    has_many :addresses, 
      inverse_of: :user, 
      dependent: :destroy, 
      index_errors: false #note here 
end 

但是它不按預期工作,換句話說,這些錯誤仍然會是這樣的:

{"addresses_attributes[0].zip_code":[{"error":"blank"}]} 

由於我重寫(或沒有)的全局配置,我期望這樣的:

{"addresses_attributes.zip_code":[{"error":"blank"}]} 

好像我不能從application.rb中覆蓋全局配置。有什麼想法嗎?

回答

0

方式的代碼在 https://github.com/rails/rails/blob/95ad242c8066e71c403d53ea634f347e357473b1/activerecord/lib/active_record/autosave_association.rb#L331

書面它會檢查其中一方被設置爲true索引錯誤。

換句話說,如果設置了全局配置,那麼無法爲一次性模型關閉它。

UPDATE: 您可以通過,而爲你解答做​​一些像

errors = model.errors.messages 
new_errors = {} 

errors.each do |key, value| 
    next unless key.to_s.include? "addresses_attributes[" 

    errors.delete key 
    new_key = key.to_s.gsub /\[\d+\]/, "" 
    new_errors[new_key] = value 
end 

errors.merge! new_errors 
+0

感謝更新錯誤。沒有辦法在模型級重寫這個配置嗎?我嘗試在我的模型中執行'Rails.configuration.active_record.index_nested_attribute_errors = false',它會編譯,但不覆蓋全局設置。 –

+0

從未嘗試過,但Rails會非常脆弱,允許配置在應用程序啓動後設置/重置。你爲什麼不重寫這個錯誤的密鑰,因爲解決方法 –

+0

你可以這樣做來改變錯誤: –