2013-10-16 29 views
1

Rails 4應用程序。form_tag表單的Rails錯誤數組

使用form_tag建立一個窗體,並想知道當窗體沒有支持我的模型時處理和顯示錯誤的典型方法(如果有的話)?

我發現的所有示例都與模型有關,典型的@model.errors.any?視圖有條件,但這不適用於form_tag

回答

2

你應該做的是:

第一加載ActiveModel包括::型號

然後進行訪問你的屬性

最後添加驗證這些屬性

例如,如果你有一個您不想將其與數據庫綁定的聯繫人模式

class Contact 

    include ActiveModel::Model 

    attr_accessor :name, :email, :message 

    validates :name, presence: true 
    validates :email, presence: true 
    validates :message, presence: true, length: { maximum: 300 } 
end 

那麼在你看來,你可以通過你的錯誤循環像你使用習慣性的ActiveRecord模型

if @model.errors.any? 
    # Loop and show errors.... 
end 
+0

這看起來不錯 - 謝謝!稍後再試 – tommyd456

1

我會建議包括不行爲模型加載ActiveModel類::驗證,但我們需要驗證。舉一個例子,考慮票務類

軌道4

class Ticket 
    include ActiveModel::Model 

    attr_accessor :title, :description 

    validate_presence_of :title 
    validate_presence_of :description 
end 

另外更多細節,如果你看到的Rails 4 activemodel的/ lib目錄/ active_model/model.rb代碼爲更好地理解爲什麼在軌道4,5「含ude ActiveModel :: Model「只足以使一個類的行爲像模型一樣。

def self.included(base) 
    base.class_eval do 
    extend ActiveModel::Naming 
    extend ActiveModel::Translation 
    include ActiveModel::Validations 
    include ActiveModel::Conversion 
    end 
end 

的Rails 3

class Ticket 
    include ActiveModel::Conversion 
    include ActiveModel::Validations 
    extend ActiveModel::Naming 

    attr_accessor :title, :description 

    validate_presence_of :title 
    validate_presence_of :description 
end 

您的機票類的行爲像模式,使您使用這些方法誤差驗證

Ticket.new(ticket_params) 
@ticket.valid? 
@ticket.errors 
@ticket.to_param 

我希望它可以幫助你解決你的問題。