我建立了一个search模型,并希望至少填写一个字段。我发现了一个有助于验证的问题,Rails: how to require at least one field not to be blank。(我尝试了所有的答案,但Voyta的答案似乎是最好的。)
验证是有效的,除非我想通过attr_accessor或attr_writer重新定义getter/setter。(我在表单上有一些虚拟属性,它们需要作为验证的一部分。)为了找出问题所在,我使用一个常规属性item_length进行了测试。如果我添加了attr_accessor :item_length,验证将停止工作。所以,我想问题是如何在不使用点符号的情况下读取属性的值。因为验证使用字符串,所以我不能使用正常的读取方式。
下面是一个代码片段:
if %w(keywords
item_length
item_length_feet
item_length_inches).all?{|attr| read_attribute(attr).blank?}
errors.add(:base, "Please fill out at least one field")
end正如我所说的,虚拟属性(length_inches和length_feet)根本不起作用,正常属性(长度)起作用,除非我重新定义getter/setter。
发布于 2012-08-26 07:31:07
正如注释中所述,使用send
array.all? {|attr| send(attr).blank?}对于那些想知道send在这种情况下是否可行的人来说,是的,它是可行的: object调用自己的实例方法。
但是api是一个很好用的工具,所以无论何时使用其他对象,都要确保在public_send中使用它们的公共send。
发布于 2012-08-26 07:29:41
您应该将read_attribute视为读取活动记录列的私有方法。否则,你应该直接使用阅读器。
self.read_attribute(:item_length) # does not work
self.item_length # ok由于您试图动态调用此方法,因此可以使用泛型ruby方法public_send来调用指定的方法
self.public_send(:item_length) # the same as self.item_lengthhttps://stackoverflow.com/questions/12126429
复制相似问题