如何在rails中使用变量作为对象属性?

时间:2010-10-12 10:53:34

标签: ruby-on-rails ruby

我有一个带有'home_address_country'属性的PaymentDetail模型,所以我可以使用

    @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}" 

表示属性名称存储在变量中。我该怎么做?

编辑

country_attribute=address_type+"_address_country"
country_list=Carmen::country_names
eval("@#{country_attribute} = #{country_list}")

2 个答案:

答案 0 :(得分:36)

  • 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")
    

<强>参考

答案 1 :(得分:4)

Rails 3的推荐方法是使用dictionary-like access

attr = @payment_detail["#{address_type}_address_country"]
attr = "new value"
@payment_detail["#{address_type}_address_country"] = attr

read_attributewrite_attribute方法仅适用于Rails 2。

相关问题