代码之家  ›  专栏  ›  技术社区  ›  Mohit Jain

如何在rails中使用变量作为对象属性?

  •  12
  • Mohit Jain  · 技术社区  · 14 年前

    我有一个PaymentDetail模型,属性是'home_address_country',所以我可以使用

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

    表示属性名存储在变量中。我该怎么做?

    编辑

    country_attribute=address_type+"_address_country"
    country_list=Carmen::country_names
    eval("@#{country_attribute} = #{country_list}")
    
    2 回复  |  直到 14 年前
        1
  •  39
  •   Harish Shetty    12 年前
    • Reading

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

      @payment_detail.read_attribute("#{address_type}_address_country")
      
    • Writing AR属性

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

      或者

      @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")
      

        2
  •  4
  •   Denis Malinovsky    11 年前

    建议使用轨道3 dictionary-like access

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

    read_attribute write_attribute 方法仅适用于Rails 2。