How ajax retrieves data from a ruils ruby ​​controller

I am not familiar with ajax and ruby ​​on reiki. I myself learned to do a project.

Now I am facing a problem, I want to use ajax to retrieve data from the controller.

I am not sure how to write the url part:

$.ajax({ type:"GET", url:"books", dataType:"json", success:function(result){ alert(result); } }) 

books is the name of my controller (a book is one of my tables)

this code works, but instead of extracting all the data from the books, I want only part of it. let's say some data in an action test in my book controller

 def test @test=books.find.last respond_do |format| format.html format.json {render ;json=>@test} end end 

but when I change the URL to books / test, I get an error: 404 not found in the console log.

How can I get some of the controller data? thank you in advance

+6
source share
1 answer

Well, what you are trying to do here is to create a non-RESTful route called test. So you need to add this to route.rb (see here for more information):

 resources :books do collection do get 'test' end end 

If you want, you can pass your parameters as follows:

 $.ajax({ type:"GET", url:"books/test", dataType:"json", data: {some_parameter: 'hello'}, success:function(result){ alert(result); } }) 

What could you use in a testing method as follows:

 def test some_parameter = params[:some_parameter] # do something with some_parameter and return the results @test=books.find.last respond_do |format| format.html format.json {render json: @test} end end 
+9
source

Source: https://habr.com/ru/post/975104/


All Articles