4

In my Rails app, I'm trying to use jQuery ajax to create a new item via the default create method in my controller.

My routes.rb looks like this:

resources :items

The server side code is still as it was generated:

  # 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 really straightforward, but I'm getting the following error:

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

I've been able to use the default update method in a similar situation without any issues. What's the problem here?

EDIT: Fixed typo in routes.rb code.

1
  • what do you see when you run rake routes? Do you see the route for items create with POST? Commented Nov 13, 2011 at 20:12

2 Answers 2

6

The example lines in your controller give a clue here.

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

The create action is simply a POST to /items.json, so you just need to change the URL you are using in your jQuery to '/items.json'.

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

Comments

1

Something is either wrong with your example or with your code! You say in routes.rbyou have

resources :workitems

Which means the path would be

/workitems/create.json

But in your script you try to call /items/create.json instead of /workitems/create.json.

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

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.