Ruby on Rails在ajax请求上出错500

时间:2012-06-01 15:58:54

标签: ruby-on-rails jquery error-handling

在应用程序启动时,我想用随机数据生成10个人。当我这样做时,我希望能够按类别异步过滤它们。这是代码:

型号代码:

class Person   
   attr_accessor :name, :text, :category, :timeStamp
end

控制器代码:

class PersonController < ApplicationController

  def index
    @persons = []
    @categories = ["history", "science", "religion"]
    10.times do
      person = Person.new
      person.name = [*('A'..'Z')].sample(8).join
      person.text = [*('A'..'Z')].sample(64).join
      person.category =  @categories.sample   
      person.timeStamp = Time.at(rand * Time.now.to_i)
      @persons.append(person)
    end
  end  

  def loadPersonsByCategory    
    @filteredPersons = @persons.where(:category => params[:category])
    render :json => @filteredPersons
  end
end

查看代码:

    <div id="personsTitle">Persons details</div>
    <div id="gridFilter">
        <label class="personText">Show persons from</label>
        <select id="filterCategory">
            <option selected="selected">All</option>
            <% @categories.each do |category| %>
                <option value="<%= category %>"><%= category %></option>
            <% end %>
        </select>
        <label class="personText">categories</label>        
    </div>
    <div id="personsGrid">
        <div class="gridRow gridHeader">        
            <div class="gridItem"><label class="personText">Name</label></div>
            <div class="gridItem"><label class="personText">Person's text</label></div>
            <div class="gridItem"><label class="personText">Category</label></div>
            <div class="gridItem"><label class="personText">Time stamp</label></div>
        </div>  
        <div id="gridBody"> 
            <% @persons.each do |person| %>
            <div class="gridRow">       
                <div class="gridItem"><label class="personText"><%= person.name %></label></div>
                <div class="gridItem"><label class="personText"><%= person.text %></label></div>
                <div class="gridItem"><label class="personText"><%= person.category %></label></div>
                <div class="gridItem"><label class="personText"><%= person.timeStamp %></label></div>
            </div>      
            <% end %>
        </div>  
        <div class="gridRow gridFooter">        
            <div class="gridItem"><label class="personText">First</label></div> 
            <div class="gridItem"><label class="personText"><</label></div> 
            <div class="gridItem"><label class="personText">1</label></div> 
            <div class="gridItem"><label class="personText">2</label></div> 
            <div class="gridItem"><label class="personText">3</label></div> 
            <div class="gridItem"><label class="personText">></label></div>     
            <div class="gridItem"><label class="personText">Last</label></div>      

        

JavaScript代码:

$(function(){
    $('#filterCategory').on('change', FilterCategories);
});

function FilterCategories(){
    $.ajax(
        {
            type: "POST",
            url: "/person/loadPersonsByCategory",
            data: { category: $(this).val() },  
            contentType: "application/json; charset=utf-8",
            dataType: "json",             
            success: function (result) {
                var persons = [];               
                for (var i = result.length; i--; ) {
                    persons.push('<div class="gridRow">' +
                                        '<div class="gridItem"><label class="personText">' + result[i].name + '</label></div>' +
                                        '<div class="gridItem"><label class="personText">' + result[i].text + '</label></div>' +
                                        '<div class="gridItem"><label class="personText">' + result[i].category + '</label></div>' +
                                        '<div class="gridItem"><label class="personText">' + result[i].timeStamp + '</label></div>' +
                                '</div>');                                                        

                }

                $('<div/>', { 'class': 'filterResult', html: persons.join('')}).appendTo('#gridBody');
            },
             error:function (xhr, ajaxOptions, thrownError){
                    alert(xhr.status);
                    alert(thrownError);
            }    
        });
}

在我尝试使用ajax过滤人员之前一切正常。我收到500内部服务器错误。 什么可能导致这个错误?非常感谢!

Plus服务器错误日志

Started POST "/Person/loadPersonsByCategory" for 127.0.0.1 at 2012-06-01 19:09:07 +0200
Processing by PersonController#loadPersonsByCategory as JSON
  Parameters: {"category"=>"religion"}
Completed 500 Internal Server Error in 1ms

NoMethodError (undefined method `where' for nil:NilClass):
  app/controllers/person_controller.rb:17:in `loadPersonsByCategory'

Routes.rb:

       TestAssignment::Application.routes.draw do
      get "person/index"

  match "/Person/loadPersonsByCategory", :controller => "person", :action => "loadPersonsByCategory"

      # The priority is based upon order of creation:
      # first created -> highest priority.

      # Sample of regular route:
      #   match 'products/:id' => 'catalog#view'
      # Keep in mind you can assign values other than :controller and :action

      # Sample of named route:
      #   match 'products/:id/purchase' => 'catalog#purchase', :as => :purchase
      # This route can be invoked with purchase_url(:id => product.id)

      # Sample resource route (maps HTTP verbs to controller actions automatically):
      #   resources :products

      # Sample resource route with options:
      #   resources :products do
      #     member do
      #       get 'short'
      #       post 'toggle'
      #     end
      #
      #     collection do
      #       get 'sold'
      #     end
      #   end

      # Sample resource route with sub-resources:
      #   resources :products do
      #     resources :comments, :sales
      #     resource :seller
      #   end

      # Sample resource route with more complex sub-resources
      #   resources :products do
      #     resources :comments
      #     resources :sales do
      #       get 'recent', :on => :collection
      #     end
      #   end

      # Sample resource route within a namespace:
      #   namespace :admin do
      #     # Directs /admin/products/* to Admin::ProductsController
      #     # (app/controllers/admin/products_controller.rb)
      #     resources :products
      #   end

      # You can have the root of your site routed with "root"
      # just remember to delete public/index.html.
      root :to => 'person#index'

      # See how all your routes lay out with "rake routes"

      # This is a legacy wild controller route that's not recommended for RESTful applications.
      # Note: This route will make all actions in every controller accessible via GET requests.
      # match ':controller(/:action(/:id))(.:format)'
    end

1 个答案:

答案 0 :(得分:2)

删除此行

contentType: "application/json; charset=utf-8",

您发布标准应用程序/ x-www-form-urlencoded数据,但告诉Rails期望JSON编码。它尝试解码数据并在此步骤失败。