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

我有一个带有属性’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}") 

  • 读取 AR属性

     @payment_detail.send("#{address_type}_address_country") 

    要么

     @payment_detail.read_attribute("#{address_type}_address_country") 
  • 编写 AR属性

     @payment_detail.send("#{address_type}_address_country=", value) 

    要么

     @payment_detail.write_attribute("#{address_type}_address_country", value) 
  • 设置实例变量

     @payment_detail.instance_variable_set("@#{address_type}_address_country", value) 
  • 获取实例变量

     @payment_detail.instance_variable_get("@#{address_type}_address_country") 

参考

  • 发送方法文档
  • read_attribute方法文档
  • write_attribute方法文档
  • instance_variable_get方法文档
  • instance_variable_set方法文档

Rails 3的推荐方法是使用类似字典的访问 :

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

read_attributeread_attribute方法仅适用于Rails 2。