1

在应用程序启动时,我想用随机数据生成 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'

路线.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
4

1 回答 1

2

删除此行

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

您发布标准的 application/x-www-form-urlencoded 数据,但告诉 Rails 期待 JSON 编码的数据。它尝试解码数据并在此步骤中失败。

于 2012-06-01T16:22:11.793 回答