dnatoli
dnatoli

Reputation: 7012

How to access the current rails object id in javascript

If I am on a view, how can I access the ID of the ruby object that is currently represented by that view?

E.g. If I am on blah.com/jobs/1 how do I get 1?

I thought about trimming the current URL but that seems way too brittle, especially given I have nested resources. The only other easy way I can think of is to have a hidden field but it seems silly to have a hidden input on a show page where there aren't any forms.

Upvotes: 9

Views: 7063

Answers (4)

cweston
cweston

Reputation: 11637

Here is a complete example, combining from the answers already provided.

Using the params[:id] and the body element, the following inline statement will produce a data-params-id attribute, that can be used generically in a layout file:

<body <%= "data-params-id=#{params[:id]}" if params.has_key?(:id) %> >

This can then be accessed with the following:

JavaScript:

var dataId = document.body.getAttribute('data-params-id');

jQuery:

var dataId = $('body').data('params-id');

Upvotes: 1

Jay
Jay

Reputation: 452

I'd suggest one of the following:

  1. As Jamsi suggested, include <%= params[:id] %> or <%= @job[:id] %> directly in your javascript:

    var id = <%= @job[:id] %>

  2. If your javascript is in a separate file, follow Mu's advice. Add the <%= @job[:id] %> to one of your view's html tags, and query it.

Upvotes: 4

James
James

Reputation: 2293

Wouldn't just <%= params[:id] %> do the trick?

Upvotes: 3

mu is too short
mu is too short

Reputation: 434665

You're right that parsing the URL is a bad idea, you're better off explicitly supplying it somewhere.

You could attach a data-job-id attribute to a standard element in the HTML, perhaps even <body>. Then your JavaScript could do things like this:

var id;
var $body = $('body');
if(id = $body.data('job-id'))
    // Do some job things.
else if(id = $body('user-id'))
    // Do some user things.

and you'd still be HTML5 compliant and you wouldn't have to muck about with hidden inputs.

You don't have to use <body> of course, your HTML probably has some top level container with a known id so you could use that instead.

Upvotes: 10

Related Questions