基于条件访问不同的模型属性

时间:2017-10-19 04:22:33

标签: ruby oop ruby-on-rails-5

我很好奇是否有一种很好的方式来访问模型的属性作为变量。

    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 }

我已尝试将该块存储在一个过程中,但我并没有这样做。有很多使用过程的经验(如果这种方法在这里工作)。谢谢你的帮助!

1 个答案:

答案 0 :(得分:0)

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

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