为什么我的Controller不传递js.erb文件的实例变量?

时间:2016-08-29 15:25:54

标签: javascript ruby-on-rails ruby highcharts

我正在构建一个由我的rails控制器的实例变量提供的html页面的高图。我收到的问题是我在控制器中设置的rails实例变量没有传递给我对应的js.erb文件。我还没有确定原因是什么。有人可以帮助确定问题可能是什么?以下是代码:

控制器

class VulnerabilitiesController < ApplicationController
  helper ProjectsHelper
  before_action :set_project_or_fail
  before_action :set_best_project_security_set
  before_action :set_releases
  before_action :set_vulnerabilities

  def index
    @release_versions = @releases.map { |r| r.version }
  end

  private 

  def set_project_or_fail
    project_id = params[:project_id] || params[:id]
    @project = Project.by_vanity_url_or_id(project_id).take
    raise ParamRecordNotFound unless @project
  end

  def set_best_project_security_set
    @best_project_security_set = @project.best_project_security_set
  end

  def set_releases
    @releases = @best_project_security_set.releases.limit(10)
  end

  def set_vulnerabilities
    @vulnerabilities = @best_project_security_set.vulnerabilities
  end
end

这是html文件:

漏洞/ index.html.haml

<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>

以下是vulnerabilities.js.erb文件的一部分:

$(function () {
$('#container').highcharts({
    chart: {
        type: 'column'
    },
    title: {
        text: 'Vulnerabilities per Version',
        align: 'left',
        style: {
            color: '#336699',
            fontSize: 16
        }
    },
    legend: {
        align:  'left',
      itemWidth: 127
    },
    xAxis: {
        categories: <%- @release_versions %>
    },

    ...........code.........

@release_versions每次都返回nil。我试过了

categories: <%- @release_versions %> categories: [<%- @release_versions %>] categories: [<%= @release_versions %>] categories: <%= @release_versions %>

这些变化都没有奏效。可能是什么问题?

1 个答案:

答案 0 :(得分:0)

要利用Rails控制器填充JS模板所需的数据,您需要直接从JS(或视图模板)调用控制器操作。

// in a view template or UJS call
<script>    
    // make an AJAX request to the '/vulnerabilities' URL
    $.ajax(...);
</script>

// VulnerabilitiesController#index action is called; index.js.erb template is rendered

// in vulnerabilities/index.js.erb
// here the instance variables from the controller action are defined
$('#container').highcharts({
    // ...
    xAxis: {
        categories: <%- @release_versions %>
    },
    // ...
};