2012-01-10 60 views
1

因此,這裏是我的非數據庫模型。使用數組對象驗證非數據庫模型

class UserApplication::CoApplicant 

    include ActiveModel::Validations 
    include ActiveModel::Conversion 

    attr_accessor :applicant, :first_name, :last_name, :email 



    def initialize(attributes = {}) 
    attributes.each do |name, value| 
     send("#{name}", value) 
    end 
    end 

    def persisted? 
    false 
    end 
end 

我正在尋找傳遞一個對象數組,看起來像這樣。

"applicant"=>{"0"=>{"email"=>"[email protected]", "last_name"=>"Jackson", "first_name"=>"Shaun"}, "1"=>{"email"=>"[email protected]", "last_name"=>"Davis", "first_name"=>"Dave"}} 

我遇到的問題是想出一種方法來驗證每個對象。這些值是來自動態生成的表的

,範圍可以從1到10行。

「0」和「1」 - 表示表格行。我正在尋找驗證屬性{email,first_name,last_name}的每個集合

我從來沒有做過這種類型的驗證之前,所以任何幫助將不勝感激!

回答

2

它看起來像你只需要實例化每個實例,然後驗證它們。這應該是簡單基於源陣列上創建它們:

applicant_data = applicants['applicant'] 
applicant_data.each do |id, attributes| 
    applicant = applicant.new(attributes) 
    applicant.valid? 
end 

你也有一個錯誤在你的任務,你要調用"#{name}"方法,而不是#{name}=方法:

def initialize(attributes = {}) 
    attributes.each do |name, value| 
    send("#{name}=", value) 
    end 
end 
+0

謝謝很多人,這是非常有幫助的。不知道爲什麼我這麼難過,但你把它清理了。 – davissp14 2012-01-11 01:22:39

+0

我之前在我的一些解決方案以及您提供的解決方案中遇到過這個問題。 「UserApplication並不缺少持續的申請人!」從我從其他來源讀到的信息來看,這是一個rails <3.1的錯誤?你有沒有經歷過這個,或者對此有所瞭解? – davissp14 2012-01-11 02:56:13

+1

看看這裏:[示例](http://stackoverflow.com/questions/4056894/rails-production-env-object-is-not-missing-constant) – tadman 2012-01-11 16:38:37