1

I guess this should be simple, but I can't figure it out

I my view there is a link that I want to trigger some ajax:

link_to( "#{sir.sir_id}" , '#', :data => {'sir-id' => sir.id}, remote: true ),

In my coffeescript I can get the value of the data-attribute in the link like so:

$ ->
  $("a[data-sir-id]").click ->
  data_sir_id = $(this).data("sir-id")

So I need the value of that variable (data_sir_id) in my controller, so I can get its associated model objects and render them in the same view

How could I achieve that?

2 Answers 2

1

You don't need to store your data in a data attribute and to make an ajax call when clicking on the link: link_to provides you a great way to make link and to pass parameters.

And by using, remote: true, it will do an ajax call without any other configuration.

link_to("#{sir.sir_id}", path_to_the_controller_action(sir_id: sir.id), remote: true)

Then, in your controller action, your data will be accessible in params[:sir_id]

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

Comments

1

Here in link_to you have passed url as '#', so if you have a particular action that you can add then you can go by above way

else you can use the following:

To specify link in view, you can use it as

link_to "#{sir.sir_id}", '#', remote: true, 'sir-id' => sir.id, class: 'sir_id_link'

In coffeescript:

$ ->
  $("sir_id_link").live "click", ->
  data_sir_id = $(@).attr("sir-id")
  $.ajax
    url: any_url
    type: "PUT"
    data:
      sir_id: data_sir_id
    success: (data) ->
      ...

Now in your controller action, you can access it as params[:sir_id].

Hope this would help you.

Thanks.

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.