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?
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]
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.