9

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.

4 Answers 4

10

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

3

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

Comments

1

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');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.