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.
.js.erb files are for controller actions, such as create, when you want javascript to be executed when the action completes. For example, when you want to submit a form via ajax and want display an alert when everything is done, you would put the $('#business_submit'). click(...) in your application.
Rails uses a technique called "Unobtrusive JavaScript" to handle attaching JavaScript to the DOM. This is generally considered to be a best-practice within the frontend community, but you may occasionally read tutorials that demonstrate other ways.
Rails UJS (Unobtrusive JavaScript) is the JavaScript library that helps Rails do its magic when we use options like remote: true for many of the html helpers. In this article I'll try to explain the main concept of how this works to make it transparent for the user.
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.
I'd suggest one of the following:
As Jamsi suggested, include <%= params[:id] %>
or <%= @job[:id] %>
directly in your javascript:
var id = <%= @job[:id] %>
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.
Wouldn't just <%= params[:id] %> do the trick?
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With