[英]Custom accessor for array element
I'm trying to create an accessor for one element from array with specific flag set to true: 我正在尝试为数组中的一个元素创建一个访问器,并将特定标志设置为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
How do i need to validate this accessor in order to hightlight missing fields in a view? 我如何验证此访问器以突出显示视图中的缺失字段?
PS I'm newbie in RoR, maybe there is another approach to such work with one element from a collection? PS我是RoR的新手,也许有另一种方法可以处理集合中的一个元素? Thanks.
谢谢。
You can have Rails magic do the work for you. 您可以让Rails magic为您完成工作。
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
The validates_associated
will validate the customer object and store the errors in entrance_object.customer.errors
(so you will have to do so some work in showing all the errors in the view). 该
validates_associated
将验证客户对象和存储中的错误entrance_object.customer.errors
(所以你必须这样做了一些工作在显示视图中所有的错误)。
See here for docs on validates_associated
. 请参阅此处以获取有关
validates_associated
文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.