2010-04-04 117 views
0

我試圖從特定標誌設置爲true陣列創建一個元素的訪問:數組元素的自定義訪問

class EntranceObject < ActiveRecord::Base 
    has_many :subscribers 

    def customer 
     self.subscribers.find(:first, :conditions => {:is_customer => true}) 
    end 

    def customer=(customer_params) 
    self.subscribers << Subscriber.new(:name => customer_params[:name], 
             :apartment => customer_params[:apartment], 
             :phone_number => customer_params[:phone_number], 
             :is_customer => true) 
    end 
end 

class Subscriber < ActiveRecord::Base 
    belongs_to :entrance_object 

    validates_presence_of :name, :apartment   
end 

我怎麼需要以hightlight中缺少的字段來驗證這個訪問一個看法?

P.S.我是RoR的新手,也許還有另外一種方法來處理這些作品中的一個元素?謝謝。

回答

0

你可以讓Rails魔術爲你做這項工作。

class EntranceObject < ActiveRecord::Base 
    has_many :subscribers 
    has_one :customer, :class_name => "Subscriber", :foreign_key => "entrance_object_id", :conditions => {:is_customer => true} 

    validates_associated :customer 
end 

validates_associated將驗證客戶對象,並存儲在entrance_object.customer.errors錯誤(所以你必須這樣做了一些工作在顯示視圖中所有的錯誤)。

有關validates_associated的文檔,請參見here

+0

這是真正的魔法!非常感謝!(% – 2010-04-05 15:38:20