简体   繁体   中英

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

"undefined method `updated_at' for nil:NilClass"

on 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:

"#{@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. Though I would advice refactoring, cause inline JS with Ruby interpolations in HAML isn't very readable and easy to debug.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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