2010-10-12 55 views
12

我有属性“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}") 

回答

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

参考

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的方法。

+0

仅供参考,我在Rails 4中测试了这个,并且#read_attribute仍然在运行 - 不确定#write_attribute。不过,我改用#send来代替。 – Dylan 2015-01-13 17:27:25

相关问题