最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to access the current rails object id in javascript - Stack Overflow

programmeradmin4浏览0评论

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/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.

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.

Share Improve this question edited Jul 28, 2012 at 18:51 mu is too short 435k71 gold badges858 silver badges818 bronze badges asked Mar 16, 2012 at 7:13 dnatolidnatoli 7,01210 gold badges60 silver badges96 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 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.

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.

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');
发布评论

评论列表(0)

  1. 暂无评论