pass variables to javascript rails

854 Views Asked by At

Using the rails cast http://railscasts.com/episodes/324-passing-data-to-javascript?autoplay=true

to pass a variable from my controller to javascript.

I have a button, when I click on it, i want it to show the number of upvotes.

Im using gon.

When I try to run it however ,my alert says the variable is not defined even though I set it in the controller

_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 ->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

Appreciate ideas, thanks

1

There are 1 best solutions below

4
mrzasa On BEST ANSWER

In this case it might be easier to pass upvote count to upDateCount

format.js {render :js =>"upDateCount(#{@source.upvotes.count})"}

and use there the argument instead of gon data.