How to use a variable as object attribute in rails?

前端 未结 2 658
无人共我
无人共我 2020-12-09 05:21

I have a PaymentDetail model with attribute \'home_address_country\', so i can use

    @payment_detail.home_address_country //where @payment_detail is object         


        
相关标签:
2条回答
  • 2020-12-09 05:33
    • 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

    • send method documentation
    • read_attribute method documentation
    • write_attribute method documentation
    • instance_variable_get method documentation
    • instance_variable_set method documentation
    0 讨论(0)
  • 2020-12-09 05:45

    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.

    0 讨论(0)
提交回复
热议问题