js.erb中的options_for_select

时间:2013-02-04 05:54:16

标签: jquery ruby-on-rails ajax

我在文件dvbd.js.erb中有这个,它工作正常。预期的行为是Dave div将在其中列出名称和id的集合。

<%@dimvers = DimensionVersion.select("name, id").where(:dimension_id => params[:id]).all %>


$("#dave").html("<%= @dimvers.collect { |d| [d.name, d.id]} %>");

这是在applications.js中,而.post调用dvbd.js.erb罚款:

jQuery.ajaxSetup({
  'beforeSend': function(xhr) { xhr.setRequestHeader("Accept", "text/javascript") }
});

$.fn.subSelectWithAjax = function() {
  var that = this;

  this.change(function() {
    $.post("/dimensions/dvbd", {id: that.val()}, null, "script");
  });
}

$(document).ready(function(){
$("#dimver_dimension_id").subSelectWithAjax();
});

但是,当我将dvbd.js.erb中的代码更改为以下内容时,它不起作用。我希望它能改变选择框#dimension_id的选项。但是,如果@dimvers碰巧没有返回匹配的记录,它只会将选择框更改为没有内容/选项。然后#dimension_id不再响应。

<%@dimvers = DimensionVersion.select("name, id").where(:dimension_id => params[:id]).all %>

$("#dimension_id").html("<%= options_for_select(@dimvers.collect {|d| [d.name, d.id] }).gsub(/n/, '') %>");

以下是show.html.erb中的代码:

<div id = 'hierarchypanel'>
    <%= collection_select(:dimver, :dimension_id, Dimension.all, :id, :title ) %>
    <%= collection_select(:dimension,:id, @dimension_versions,:id, :name)  %>
</div>

2 个答案:

答案 0 :(得分:1)

尝试将html传递给escape_javascript

$("#dimension_id").html("<%= escape_javascript options_for_select(@dimvers.collect { |d| [d.name, d.id] }) %>");

答案 1 :(得分:0)

最好的方法是使用partial并在partial中使用select_tag,然后从.js.erb中调用该部分

前:

#_select_partial.erb
<%= options_for_select(@dimvers.collect {|d| [d.name, d.id] }).gsub(/n/, '') %>

#dvbd.js.erb
$("#dave").html("<%= raw escape_javascript(render(:partial => 'select_partial')) %>")