Rails 并将数据传递给 Javascript

发布于 2025-01-08 21:46:00 字数 1144 浏览 0 评论 0原文

我有一个根据特定条件列出美国所有州的视图。在同一视图中,我包含了一个 SVG 地图,它根据状态结果集拾取颜色。状态列表部分映射到我的控制器中的方法 A,而 JavaScript 映射链接到同一控制器中的不同方法 B。但是我的方法 B 需要从 A 获取返回的状态列表。如何在两个方法之间共享变量? 我尝试使用 before_filter 方法来加载一些实例变量,但这不起作用。

任何帮助将不胜感激。

代码:

def reports
    @query   = @report.search_query
    @results = @query.results(:page => params[:page], :results_per_page => 200).hits
    @state = Array.new
    @results.each do |r|
        @state << r.result.state.abbreviation
    end
    @finalstate = @state.uniq 
end

def data
    state_groups = State.select('abbreviation,premium').inject({}) do |groups, state|
        groups["#{state.abbreviation}"] = {
            :abbreviation => state.abbreviation,
            :group => @finalstate.include?(state.abbreviation) ? "found" : "not",
            :clickable => "true"
        }
    groups
    end
    render :json => state_groups.to_json
end

在我的部分中,我有这样的内容:

content_for :footer_scripts do = javascript_bundle :bundle_report

我的 JavaScript 地图涉及获取 JSON 的 data 方法。这个 JSON 返回一个 null,这就是我陷入困境的地方。

I have a view that lists all the states of US based on a certain condition. In the same view I have included an SVG map which picks up color based on the result set of states. The state list partial is mapped to a method A in my controller, while the JavaScript map is linked to a different method B in the same controller. However my method B needs to get the returned state lists from A. How can I share the variable between the two methods?
I tried a before_filter method to load up some instance variables, but that didn't work.

Any help will be appreciated.

Code:

def reports
    @query   = @report.search_query
    @results = @query.results(:page => params[:page], :results_per_page => 200).hits
    @state = Array.new
    @results.each do |r|
        @state << r.result.state.abbreviation
    end
    @finalstate = @state.uniq 
end

def data
    state_groups = State.select('abbreviation,premium').inject({}) do |groups, state|
        groups["#{state.abbreviation}"] = {
            :abbreviation => state.abbreviation,
            :group => @finalstate.include?(state.abbreviation) ? "found" : "not",
            :clickable => "true"
        }
    groups
    end
    render :json => state_groups.to_json
end

In my partials I have something like this:

content_for :footer_scripts do
= javascript_bundle :bundle_report

My JavaScript map involves the data method to get the JSON. This JSON returns a null, and that is where I am stuck.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文