使用rails cast here
将变量从我的控制器传递给javascript。
我有一个按钮,当我点击它时,我希望它显示upvotes的数量。
我正在使用gon。
当我尝试运行它时,我的警告说即使我在控制器中设置了变量,也没有定义变量
_source.html.erb
<div class="panel-body">
<%= include_gon(:init => true) %>
<%=source.source %>
<% @count = pluralize(source.upvotes.count,"upvote") %>
<div id="count"><%= @count %></div>
<%= button_to '+1', upvote_source_path(source), method: :post,remote: true %>
<p><%= link_to "delete", [source.fact, source], method: :delete, data:{confirm: "are you sure?"} %></p>
</div>
application.html.erb
<!DOCTYPE html>
<html>
<head>
<title>Sourcemonkey</title>
<%= include_gon(:init => true) %>
<%= csrf_meta_tags %>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
<%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
</head>
<body>
<%= yield %>
</body>
</html>
sources_controller.rb - &gt; upvotes action
def upvote
@source = Source.find(params[:id])
@source.upvotes.create
gon.count = @source.upvotes.count
respond_to do |format|
format.js {render :js =>"upDateCount()"}
format.html { redirect_to :none}
end
end
upvote.js.erb
function upDateCount(){
alert(gon.count)
}
的routes.rb
Rails.application.routes.draw do
# mount Ckeditor::Engine => '/ckeditor'
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
root to: "facts#index"
resources :facts do
resources :sources
end
resources :sources do
member do
post 'upvote'
end
end
resources :upvote
end
欣赏想法,谢谢
答案 0 :(得分:1)
在这种情况下,将upvote计数传递给upDateCount
format.js {render :js =>"upDateCount(#{@source.upvotes.count})"}
并在那里使用参数而不是gon
数据。