如何在rails中使用变量作为对象属性? [英] How to use a variable as object attribute in rails?
本文介绍了如何在rails中使用变量作为对象属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个带有home_address_country"属性的 PaymentDetail 模型,所以我可以使用
I have a PaymentDetail model with attribute 'home_address_country', so i can use
@payment_detail.home_address_country //where @payment_detail is object of that model.
我想使用这样的东西:---
I want to use something like this:---
country_attribute=address_type+"_address_country" //where address type is equal to 'home'
@payment_detail."#{country_attribute}"
表示属性名称存储在变量中.我该怎么做?
编辑
country_attribute=address_type+"_address_country"
country_list=Carmen::country_names
eval("@#{country_attribute} = #{country_list}")
推荐答案
阅读 AR 属性
Reading AR attribute
@payment_detail.send("#{address_type}_address_country")
OR
@payment_detail.read_attribute("#{address_type}_address_country")
写入 AR 属性
Writing AR attribute
@payment_detail.send("#{address_type}_address_country=", value)
OR
@payment_detail.write_attribute("#{address_type}_address_country", value)
设置实例变量
Setting instance variable
@payment_detail.instance_variable_set("@#{address_type}_address_country", value)
获取实例变量
Getting instance variable
@payment_detail.instance_variable_get("@#{address_type}_address_country")
- send 方法 文档
- read_attribute 方法文档
- write_attribute 方法文档
- instance_variable_get 方法文档
- instance_variable_set 方法文档
- send method documentation
- read_attribute method documentation
- write_attribute method documentation
- instance_variable_get method documentation
- instance_variable_set method documentation
参考
这篇关于如何在rails中使用变量作为对象属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文