簡體   English   中英

Ruby on Rails具有ActiveRecord錯誤處理的怪異行為

[英]Ruby on Rails bizarre behavior with ActiveRecord error handling

誰能解釋為什么會這樣?

mybox:$ ruby script/console
Loading development environment (Rails 2.3.5)
>> foo = Foo.new
=> #<Foo id: nil, customer_id: nil, created_at: nil, updated_at: nil>
>> bar = Bar.new
=> #<Bar id: nil, bundle_id: nil, alias: nil, real: nil, active: true, list_type: 0, body_record_active: false, created_at: nil, updated_at: nil>
>> bar.save
=> false
>> bar.errors.each_full { |msg| puts msg }
Real can't be blank
Real You must supply a valid email
=> ["Real can't be blank", "Real You must supply a valid email"]

到目前為止,這是完美的,這就是我希望讀取的錯誤消息。 現在更多:

>> foo.bars << bar
=> [#<Bar id: nil, bundle_id: nil, alias: nil, real: nil, active: true, list_type: 0, body_record_active: false, created_at: nil, updated_at: nil>]
>> foo.save
=> false
>> foo.errors.to_xml
=> "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<errors>\n  <error>Bars is invalid</error>\n</errors>\n"

那是我不知道的。 與上面顯示的錯誤消息相比,[為什么我不能得到Bars無效],[“ Real不能為空”,“ Real您必須提供有效的電子郵件”]等。

我的控制器僅具有一個respond_to方法,其中包含以下內容:

 format.xml  { render :xml => @foo.errors, :status => :unprocessable_entity }

我該如何輸出真正的錯誤消息,以便用戶對自己的錯誤做些了解? 如何在控制器中編寫render方法以顯示所有適當的錯誤消息?

我想你在用

validates_associated:bar在您的foo.rb模型中

所以它只給出“酒吧是無效的”

檢查酒吧的錯誤消息,您必須在您的以下操作

視圖

<%= error_messages_for :foo, :bar %>

控制者

foo.bar.errors.to_xml

&跳過“ bar is invalid”消息,將以下方法放在foo.rb中

  def after_validation
    # Skip errors that won't be useful to the end user
    filtered_errors = self.errors.reject{ |err| %w{ bar }.include?(err.first) }
    self.errors.clear
    filtered_errors.each { |err| self.errors.add(*err) }
  end

這是因為bar的錯誤存儲在bar對象中。 要獲取這些錯誤,您必須執行以下操作:

foo.bar.each do |bar|
  bar.errors.each_full { |msg| puts msg }
end

這一切對我來說都是令人費解的,但是我還沒有找到將所有錯誤匯總到一個列表中的最佳方法(除了自己處理之外)。 我了解其背后的原因(因為每個對象應該只知道它自己的錯誤)。 我通常要做的是each_full_with_associations ActiveRecord::Errors並創建一個新的each_full_with_associations函數,將其全部返回。

當您在帶有嵌套字段的表單上看到它時,這一切都是有意義的。 在這種情況下,錯誤會正確顯示,並且一切正常。

我們曾經覆蓋特定模型中的errors方法,如果我們也需要子對象的錯誤,像這樣

class Foo < ActiveRecord::Base

  alias :errors_without_children :errors

  def errors
    self.bars.each do |i|
      i.errors.each_full do |msg|
        errors_without_children.add_to_base msg
      end
    end
    errors_without_children
  end

end

您仍然可以對其進行更多優化。 但這已經將所有bar對象的錯誤消息添加到foo。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM