Ruby if condition not working properly in javascript file

不想你离开。 提交于 2019-12-24 02:58:36

问题


Controller:

def AjaxView
  @vars= Var.find(:all,:conditions => { :varName=> "one" },:select=>(params[:col]))
  @col = params[:col]
  respond_to do |format|
    format.js { render :layout=>false }
  end
end

AjaxView.js.erb

  if('<%= @col %>' == 'colName'){
    $("#3").text("<%= escape_javascript(render(:partial => "var")) %>");
  } else if('<%= @col %>' == 'colName2'){
    $("#2").text("<%= escape_javascript(render(:partial => "var1")) %>");
  }

View Partial:

_var.html.erb

 <%= @vars[0].colName %>

_var1.html.erb

  <%= @vars[0].colName2 %>

If I change this code

$("#3").text("<%= escape_javascript(render(:partial => "var") %>"); 

to alert("hi_one"); and

$("#2").text("<%= escape_javascript(render(:partial => "var1") %>");

to alert("hi_two");

it works fine.

but when I put the above code, it runs both the code each time, not sure why, is it compiling it or what ? and whats the way out?

Render Output:

Rendered test/_var.html.erb (16.0ms) Rendered test/AjaxView.js.erb (19.0ms) Completed 500 Internal Server Error in 38ms

ActionView::Template::Error (missing attribute: colName): 1: <%= @ vars[0].col %>

Javascripty output in Firebug is 500 error


回答1:


Currently your condition if('<%= @col %>' == 'colName') is client-side JavaScript.

What this means is that in

if('<%= @col %>' == 'colName'){
    $("#3").text("<%= escape_javascript(render(:partial => "var")) %>");
} else if('<%= @col %>' == 'colName2'){
    $("#2").text("<%= escape_javascript(render(:partial => "var1")) %>");
}

both render :partial calls are executed server-side in order for Rails to render the template but then when the generated JavaScript executes client-side the logic determines which .text call executes. This means that the contents of both partials must be valid in both scenarios (even the one that eventually isn't going to be used.)

To fix it, either include both colName and colName2 in your :select or change the if to be server-side so that you then respond with just one 1 of the .text lines. e.g.

<% if @col == 'colName' %>
  $("#3").text("<%= escape_javascript(render(:partial => "var")) %>");
<% elsif @col == 'colName2' %>
  $("#2").text("<%= escape_javascript(render(:partial => "var1")) %>");
<% end %>


来源:https://stackoverflow.com/questions/8712852/ruby-if-condition-not-working-properly-in-javascript-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!