Using Rails by default: routing resources to create a record using jQuery ajax

In my Rails application, I am trying to use jQuery ajax to create a new element using the default create method in my controller.

My routes.rb as follows:

 resources :items 

Server-side code is still as it is created:

  # POST /items # POST /items.json def create @item = Item.new(params[:item]) respond_to do |format| if @item.save format.html { redirect_to @item, :notice => 'Item was successfully created.' } format.json { render :json => @item, :status => :created, :location => @item } else format.html { render :action => "new" } format.json { render :json => @item.errors, :status => :unprocessable_entity } end end end 

And my JavaScript:

 $("#capture_input").focusout(function() { var description = $(this).val(); $.ajax({ type: "POST", url: '/items/create.json', data: { item: { description : description } }, dataType: 'json', success: function(msg) { alert( "Data Saved: " + msg ); } }); }); 

This seems very simple, but I get the following error:

 ActionController::RoutingError (No route matches [POST] "/items/create.json"): 

I could use the default update method in a similar situation without any problems. What is the problem?

EDIT: Fixed a typo in the route.rb file.

+4
source share
2 answers

The following are examples of strings in your controller.

 # POST /items # POST /items.json def create ... 

The create action is just a POST for /items.json, so you just need to change the URL you use in jQuery to '/items.json'.

+6
source

Something is wrong with your example or with your code! You say in routes.rb that you have

 resources :workitems 

This means that the path will be

 /workitems/create.json 

But in a script, you are trying to call /items/create.json instead of /workitems/create.json .

I think you should check your .rb routes or your example.

+1
source

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


All Articles