Leo
Leo

Reputation: 2103

Getting an id of an ruby object with jquery

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

Upvotes: 0

Views: 532

Answers (3)

Marty Cortez
Marty Cortez

Reputation: 2343

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

Upvotes: 1

house9
house9

Reputation: 20614

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

Upvotes: 0

Nick Veys
Nick Veys

Reputation: 23939

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.

Upvotes: 3

Related Questions