Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
435 views
in Technique[技术] by (71.8m points)

ruby - 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}")
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  • 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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...