アプリケーションの起動時に、ランダムなデータを使用して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