Question

In my Rails app, I'm trying to view a model via its' URL /models/:id.

I'm generating the URL two different ways: in JavaScript and Rails, though it seems to be randomly that the controller does not recognize the id-parameter in its' action.

1st way in JavaScript:

<a href='/conversations/" + conv_id + "'>" + conv_subject + "</a>

where conv_id is the id of the model I want to visit.

Same bug occurs when I'm doing it the Rails way:

<%= link_to "Conv" , conversation_path(22) %>

Where I've just put the id of the conversation by hand.

The controller action looks like this:

def show
   gon.current_user_id = current_user.id
   gon.conversation_id = params[:id]
 end

I'm displaying the contents via AJAX. There's more code handling that in the action. The key point is, though, that the controller does not seem to recognize params[:id]. Only after I pressed F5, after the first visit of /conversations/:id, the controller recognizes it.

Thanks in advance!

EDIT:

It happens that the controller recognizes the id, though GON wouldn't pass it to the javascript in time

EDIT:

The problem probably lies under the asset-pipeline, because all my scripts requiring GON are laying in the pipeline, which is only reloaded with the proper GON-Variables, after I've pressed F5

EDIT:

Since the problem lies in my JavaScript here's the approach I've taken so far. I tried to outsource all GON-Variables used in the Asset-Pipeline via function-parameters, which are passed to the functions in the views.

Asset-Pipeline function:

// Load n messages
function loadMessages(page, n, conv_id) {
    $.ajax({
        url: '/conversations/ajax/fetch_messages',
        data: 'n=' + n + '&page=' + page + '&id=' + conv_id,
        dataType: 'JSON',
        type: 'GET'
        ...
    });
}

View function:

<script>
    $(function() {
        // Load 10 Messages when the page is loaded for the first time
        loadMessages(1, 10, gon.conversation_id);
    });
</script>

EDIT:

This is what GON gives me when rails says it doesn't know the ID. It's kind of weird.

What the debugger tells me:

//<![CDATA[
window.gon={};gon.current_user_id=3;gon.conversation_id=22;
//]]>

What the inspector tells me:

//<![CDATA[
window.gon={};gon.load_n_feedbacks_path="/feedbacks/ajax/load_n_feedbacks";gon.user_id="3";
//]]>
Was it helpful?

Solution 2

I've been including GON via include_gon in my application.html.erb.

The html was not refreshing when clicking on links and thus weren't the GON-Variables. I simply followed this answer: gon is not defined error in javascript. It says to put all your include_gons in the views who require it in their JS.

OTHER TIPS

Your problem is you're passing a naked object to the link_to url option. Rails either needs a URL helper, :action / :controller arguments or a pure URL

You're best using something like this:

<%= link_to "Conv" , conversation_path(22) %>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top