Rails 并将数据传递给 Javascript
我有一个根据特定条件列出美国所有州的视图。在同一视图中,我包含了一个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论