Search code examples
javascriptruby-on-railsgon

Why is this controller variable not getting through to this javascript code?


I am trying now to use my javascript to render a new view on click of an element, with this code;

$(document).ready(function() {
    $('.link-panel').click( function() {
        window.location.replace('/quotes/'+gon.gon_quote_id);
    });
});

and i get the following error:

Couldn't find Quote with 'id'=undefined [WHERE "quotes"."user_id" = $1]

quote_controller.rb:

  def show
    @quote = current_user.quotes.find(params[:id])
    gon.gon_quote_id = @quote.id
  end

def index
@quotes = current_user.quotes.all
# how to pass the individual quote object's id to gon here

end

I think that it must be the way that I've given the url argument to the replace method, can you help me with what it is that I'm doing wrong?

(gon setup is working fine as alert tests demonstrate.)

Thanks


Solution

  • The script does not know that it's meant to access a variable from rails, you have to do it like so:

    $(document).ready(function() {
        $('.link-panel').click( function() {
            window.location.replace('/quotes/'+<%= gon.gon_quote_id %>);
        });
    });