Mohit Jain
Mohit Jain

Reputation: 43959

How to use a variable as object attribute in rails?

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

Means attribute name is stored in a variable. How can i do this?

EDIT

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

Upvotes: 14

Views: 11721

Answers (2)

Denis Malinovsky
Denis Malinovsky

Reputation: 6270

Recommended way for Rails 3 is to use dictionary-like access:

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

read_attribute and write_attribute methods work for Rails 2 only.

Upvotes: 4

Harish Shetty
Harish Shetty

Reputation: 64373

  • Reading AR attribute

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

    OR

    @payment_detail.read_attribute("#{address_type}_address_country")
    
  • 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")
    

Reference

Upvotes: 43

Related Questions