手动定义getter/setter(attr_accessor或attr_writers)时如何使用read_attribute [英] How to use read_attribute when manually defining getter/setter (attr_accessor or attr_writers)
问题描述
我建立了一个search
模型,并希望至少填写一个字段.我发现了一个有助于验证的问题,
I set up a search
model and want to require at least one field is filled out. I found a question that helps with the validation, Rails: how to require at least one field not to be blank. (I tried all answers, but Voyta's seems the best.)
除了我要通过attr_accessor
或attr_writer
重新定义getter/setter时,验证有效. (我在表单上有一些虚拟属性,需要与验证分开.)为了弄清楚问题出在哪里,我测试了一个具有常规属性item_length
的属性.如果添加attr_accessor :item_length
,验证将停止工作.因此,我想问题是如何在不使用点表示法的情况下读取属性的值.由于验证使用字符串,因此我无法使用正常的读取方式.
The validation is working, except when I want to redefine the getter/setter via attr_accessor
or attr_writer
. (I have virtual attributes on the form that need to be apart of the validation.) To figure out what the problem is, I tested with an attribute that is a regular attribute item_length
. If I add attr_accessor :item_length
, the validation stops to work. So, I guess the question is how to I read an attribute's value without using dot notation. Since the validation uses strings, I can't use the normal way of reading.
这是一个代码段:
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)根本不起作用,正常属性(length)起作用,除非我重新定义getter/setter.
Like I said, the virtual attrbutes (length_inches and length_feet) do not work at all, and the normal attribute (length) works except if I redefine the getter/setter.
推荐答案
如注释中所述,使用send
array.all? {|attr| send(attr).blank?}
对于那些想知道send
在这种情况下是否可以使用的人,是的,它是:对象调用其自己的实例方法.
For those wondering if send
is ok in this case, yes it is: object calls its own instance methods.
但是send
是一个非常有用的工具,因此,当您与其他对象一起使用时,请确保将其公共api与public_send
But send
is a sharp tool, so whenever you use with other objects, ensure you use their public api with public_send
这篇关于手动定义getter/setter(attr_accessor或attr_writers)时如何使用read_attribute的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!