如何在rails中使用变量作为对象属性?
问题描述:
我有属性“home_address_country”一个PaymentDetail模式,这样我就可以使用如何在rails中使用变量作为对象属性?
@payment_detail.home_address_country //where @payment_detail is object of that model.
我想用这样的:---
country_attribute=address_type+"_address_country" //where address type is equal to 'home'
@payment_detail."#{country_attribute}"
手段属性名称存储在一个变量。我怎样才能做到这一点?
EDIT
country_attribute=address_type+"_address_country"
country_list=Carmen::country_names
eval("@#{country_attribute} = #{country_list}")
答
-
Reading AR属性
@payment_detail.send("#{address_type}_address_country")
OR
@payment_detail.read_attribute("#{address_type}_address_country")
-
Writing AR属性
@payment_detail.send("#{address_type}_address_country=", value)
OR
@payment_detail.write_attribute("#{address_type}_address_country", value)
-
Setting实例变量
@payment_detail.instance_variable_set("@#{address_type}_address_country", value)
-
Getting实例变量
@payment_detail.instance_variable_get("@#{address_type}_address_country")
参考
- 发送方法documentation
- read_attribute方法documentation
- write_attribute方法documentation
- instance_variable_get方法documentation
- instance_variable_set方法documentation
答
为Rails 3推荐的方法是使用dictionary-like access:
attr = @payment_detail["#{address_type}_address_country"]
attr = "new value"
@payment_detail["#{address_type}_address_country"] = attr
read_attribute
和write_attribute
只适用于Rails 2的方法。
仅供参考,我在Rails 4中测试了这个,并且#read_attribute仍然在运行 - 不确定#write_attribute。不过,我改用#send来代替。 – Dylan 2015-01-13 17:27:25