2010-10-12 12 views
12

Mam modelu PaymentDetail z atrybutem „home_address_country”, więc można używaćJak używać zmiennej jako atrybutu obiektu w szynach?

@payment_detail.home_address_country //where @payment_detail is object of that model. 

Chcę używać coś takiego: ---

country_attribute=address_type+"_address_country" //where address type is equal to 'home' 
@payment_detail."#{country_attribute}" 

Środki nazwy atrybutów są przechowywane w zmienna. Jak mogę to zrobić?

EDIT

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

Odpowiedz

34
  • Reading atrybut AR

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

    lub

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

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

    lub

    @payment_detail.write_attribute("#{address_type}_address_country", value) 
    
  • Setting przykład zmienna

    @payment_detail.instance_variable_set("@#{address_type}_address_country", value) 
    
  • Getting przykład zmienna

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

odniesienia

4

Zalecany sposób do szyny 3 jest użycie dictionary-like access:

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

read_attribute i write_attribute metody działają tylko w Rails 2.

+0

FYI, testuję to w Railsach 4 i #read_attribute nadal działa - nie mam pewności co do #write_attribute. Zamiast tego przełączam się na #send. – Dylan

Powiązane problemy