2017-10-19 55 views
0

我很好奇,如果有一種很好的方式來訪問模型的屬性作爲變量。基於條件訪問不同的模型屬性

if I18n.locale == :ja 
     pref = Prefecture.all.find { |pr| pr.name == province } 
    else 
     pref = Prefecture.all.find { |pr| pr.name_e == province } 
    end 

事情是這樣的僞代碼:

...find { |pr| pr.(I18n.locale == :ja ? name : name_e) == province } 

我試圖存儲塊的一個進程,但我不使用有特效(如果這種做法會在這裏工作)很多經驗。感謝您的幫助!

+0

這是您正在訪問的ActiveRecord模型嗎? – plasticide

回答

0
attr = 
case I18n.locale 
when :ja then :name 
else :name_e 

pref = Prefecture.find {|pr| pr.send(attr) == province} 
+0

啊,我忘了#send!感謝您的建議,我認爲這基本上是我在尋找的。 –