ruby-on-rails - Rails - 'send' 和 'try' 的混合

标签 ruby-on-rails dynamic attributes

我有一个可能为零的对象。在下一行中,我根据某些条件动态获取对象的任何一个参数。我在 if else 块中使用 object.try()。现在我想使用 send() 来实现一些高效的代码。

form_name = 'parent' ( received from argument )
mes_record = Mark.first ( this can be nil )

if x == condition_1
    mes_record.parent
elsif x == condition_2
    mes_record.brother
elsif x == condition_3
    mes_record.sister
else
    mes_record.father
end

现在我想避免使用 if else 阶梯并使用发送。
 if mes_record.present?
      mes_record.send("#{form}")
 else
      mes_record = 'not available'
 end

我正在寻找类似尝试的东西。
   mes_record.try("dynamically substitute the attribute name here.") || 'not available'

有什么帮助吗?!

最佳答案

尝试了一个小时后,我找到了解决方案。

向 Rails 尝试方法致敬。

mes_record.try(:send, "#{form}") || '无法使用'

关于ruby-on-rails - Rails - 'send' 和 'try' 的混合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29194619/

相关文章:

jquery - 如何在单独的文件中查看此脚本?

javascript - 动态服务器时间

python - ansible 动态库存错误

mysql - 如何使用MySQL设计动态表

ruby-on-rails - 如何在rails 3中实时推送内容

ruby-on-rails - 使用 Rails 服务器进行 AngularJS 模板翻译的方法

google-chrome-extension - 浏览器插件/扩展/插件一次查看所有元素的 id

html - Angularjs 属性文字值与表达式评估

attributes - @nogc 属性是否在 d 中实现?

ruby-on-rails - rails + CarrierWave : NoMethodError: undefined method `image_url' for nil:NilClass