简体   繁体   English

javascript对haml中的ruby对象的评估抛出undefine方法异常

[英]javascript evaluation of ruby object inside haml throw undefine method exception

I have a javascript that should change an haml element only when ruby object is define unfortunately the "#{project.builds.last.updated_at}" is been evaluated when the page is rendered ragrdeless to the if condition that is false, and therefore I am getting 我有一个javascript,只有在定义了ruby对象时,才应该更改haml元素。不幸的是,当页面呈现为无条件至if条件为false时,将评估“#{project.builds.last.updated_at}”,因此我越来越

"undefined method `updated_at' for nil:NilClass" “ nil:NilClass的未定义方法`updated_at'”

on project.build.last. 在project.build.last上。

if ((#{@project.builds.size} && #{@project.builds.size}) > 0){  
  document.getElementById("lastSave").innerHTML = "#{@project.builds.last.updated_at}";
}

any idea how I can force the evaluation to be in real time? 知道如何强制实时评估吗?

You can use try method: 您可以使用try方法:

"#{@project.builds.last.try(:updated_at)}"

It will generate empty string if there are no builds , but it doesn't matter since this part of JS won't be executed under this condition. 如果没有builds ,它将生成一个空字符串,但这并不重要,因为在这种情况下不会执行JS的这一部分。 Though I would advice refactoring, cause inline JS with Ruby interpolations in HAML isn't very readable and easy to debug. 尽管我建议您进行重构,但由于HAML中的带Ruby插值的内联JS不太易读且易于调试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM