如何使用read_attribute时手动限定的getter / setter(attr_acces

2019-09-21 16:35发布

我建立了一个search模式,并且要至少需要一个字段填写。 我发现一个问题,利用有效的帮助, Rails的:如何要求至少一个字段不为空 。 (我尝试了所有的答案,但Voyta酒店的似乎是最好的。)

验证工作,除非我要重新通过的getter / setter attr_accessorattr_writer 。 (我有需要分开验证的形式虚拟属性)。为了弄清楚是什么问题,我与是一个普通的属性的属性测试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

就像我说的,虚拟attrbutes(length_inches和LENGTH_FEET)不会在所有的工作,而通常属性(长度)的作品,除非我重新定义的getter / setter。

Answer 1:

正如评论指出,使用send

array.all? {|attr| send(attr).blank?}

对于那些想,如果send是在这种情况下好了,是的,它是:对象调用它自己的实例方法。

但是send是锋利的工具,所以每当你与其他物体使用,确保你使用他们的公共API与public_send



Answer 2:

你应该考虑read_attribute作为阅读活动记录列的私有方法。 否则,你应该总是直接使用的读者。

self.read_attribute(:item_length) # does not work
self.item_length # ok

既然你想要动态调用该方法,可以使用常规方法红宝石public_send调用指定的方法

self.public_send(:item_length) # the same as self.item_length


文章来源: How to use read_attribute when manually defining getter/setter (attr_accessor or attr_writers)