0

So i have ruby code that simply writes all of my objects down in some view

%ul
    - @user.posts.each do |post|
        %li {data: {role: "choosable-post"}}
            = post.title

Now the trick is those are not posts itself, just the titles. how can i get the id of a specific post with jQuery? Of course User has_many :posts so every post has an id of its own.

i figured it could start like this...

$("li[data-role=choosable-post]").onclick ->
    my_object = @(this)

but i dont really know if its a good direction or how to continue if it is...

2
  • Does the post have an id attribute in ruby? If so then do what they say below. Commented Sep 26, 2013 at 18:40
  • jQuery runs client-side, and only has access to the DOM, barring AJAX. Ruby runs server-side, and will have finished its execution long before the browser starts executing any JavaScript. The two cannot interact directly. Commented Sep 26, 2013 at 18:44

3 Answers 3

3

You're already using data fields, it's extremely common to store information about objects in there:

%ul
  - @user.posts.each do |post|
    %li {data: {role: "choosable-post", id: "#{post.id}"}}
      = post.title

Now it's in the element you select, so it should be something like:

$("li[data-role=choosable-post]").onclick ->
  my_object_id = $(this).data('id')

That JavaScript is untested, but should give you the idea.

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

Comments

1
%ul
  - @user.posts.each do |post|
    %li {data: {role: "choosable-post", id: "#{post.id}"}}
      = post.title

Will give you the id, and then, in your HTML, you should be able to find the id as shown in this fiddle: http://jsfiddle.net/gG2gs/2/

Comments

0

render the post id into a data attribute

%li {class: "post-container", data: {role: "choosable-post", post-id: post.id}}

retrieve that client side with jquery

$(".post-container").click ->
  li = $(this)
  console.log(li.data('post-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.