开发者

No route matches [POST] - Sending data to Ruby on Rails

I'm trying to send data to my Ruby on Rails application via an AJAX POST request. This w开发者_JS百科orks fine on the index page where it just accepts the POST request and takes the parameter for usage like params[:MyParam], however when trying to do the exact same thing in my show action, I get the error:

No route matches [POST]

I'm sending the POST request like so:

 <% if !params[:recData] %>
var PostDone = false;
 <% end %>
 $(document).ready(function() {
   $.post(document.URL, { recData: "POST REQUEST!" }, function(response) { 
  if(PostDone == false) {
    document.write(response);
    PostDone = true;
  }
  });
 });

I'm kind of new to AJAX and Rails, so a helping hand would be much appreciated.


Ok first of all if you read this you know that resources :products adds following route

Verb    Path    action  used for
POST  /products create  create a new product

also routes are matched from the top so since you have

resources :products # matches '/products' via POST
match '/products' => 'products#index', :via => :post

each time you have POST request to the '/products' first route defined with resources :products is matched

show action works because it is also defined with resources :products but only for GET method

now workarounds

change order to

match '/products' => 'products#index', :via => :post
resources :products # never matched '/products' via POST

or use :except

resources :products, :except => :create # does not match '/products' via POST
match '/products' => 'products#index', :via => :post

in both cases your create action will newer be matched


Try replacing document.URL in your $.post function with the actual URL you are posting to, e.g. inserting it via Rails like this:

$.post('<%= objects_path %>', ...

Of course replace objects_path with whatever your named route is called.

The reason you are getting the error is probably that the index and create actions have the same URL (only with a different HTTP verb), but the show action has a completely different one. In your jQuery you are always using the URL of the current page which just happens to work with the index action, but not on any other page.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜