2010-10-12 95 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