我正在Rails 3.2.20應用程序中進行一些基本的crud工作,我跟蹤LostCalls。我有一切設置和工作,但當試圖實現搜索方法時,我的控制器正在拋出一個NilClass,當我嘗試分頁。未定義的方法`paginate'for nil:NilClass搜索時
這是我的模型,視圖和控制器的樣子。
lostcalls_controller.rb
def index
@lostcalls = LostCall.report(params[:search])
respond_to do |format|
format.html do
@lostcalls = @lostcalls.paginate(:per_page => params[:per_page] || 1, :page => params[:page]).order('call_date ASC')
end
format.csv { send_data LostCall.to_csv(@lostcalls) }
format.pdf do
pdf = LostCallPdf.new(@lostcalls)
send_data pdf.render, filename: "lostcalls",
type: "application/pdf",
disposition: "inline"
end
end
end
lost_call.rb模型
index.html.erb
<h3>Lost Call Log</h3>
<%= render 'search' %>
<%= render 'results' %>
_search.html.erb
<div>
<%= form_tag lostcalls_path, :method => 'get' do %>
<p>
<%= text_field_tag "search[start_date]", params[:search].try(:[], :start_date), :placeholder => 'Start Date', :class => 'input-large search-query ', id: 'start_date_select' %>
to
<%= text_field_tag "search[end_date]", params[:search].try(:[], :end_date), :placeholder => 'End Date', :class => 'input-large search-query', id: 'end_date_select' %>
</p>
<p>
<%= select_tag "search[facility_name]", options_from_collection_for_select(Facility.order(:facility_name), :id, :facility_name, selected: params[:search].try(:[], :facility_name)), prompt: "Any Facility" %>
</p>
<p>
Results Per Page
<%= select_tag "per_page", options_for_select([["10", 10], ["25", 25] , ["50", 50], ["100", 100], ["All", 100000]], selected: params[:per_page]), class: "span1" %>
<%= submit_tag "Search", :name => nil, :class => 'btn' %> <%= link_to "Export to CSV", lostcalls_path(params.merge(format: "csv")), :class => "btn btn-info" %> <%= link_to "Export To PDF", lostcalls_path(params.merge(format: "pdf")) , :class => 'btn btn-warning' %> <%= link_to "New Entry", new_lostcall_path, class: 'btn btn-danger' %>
</p>
<% end %>
</div>
_results.html.erb
<table class="table table-striped">
<thead>
<tr>
<th>Call Date</th>
<th>Facility</th>
<th>Call Details</th>
<th>Entered By</th>
<th></th>
</tr>
</thead>
<tbody>
<% @lostcalls.each do |l| %>
<tr>
<td><%= l.call_date.strftime("%m/%d/%y") %></td>
<td><%= l.facility.try(:facility_name) %></td>
<td><%= l.call_details %></td>
<td><%= l.entered_by %></td>
<td><%= link_to 'View', lostcall_path(l), :class => 'btn btn-info btn-mini'%></td>
</tr>
<% end %>
</tbody>
</table>
<%= will_paginate @lostcalls, :renderer => BootstrapPagination::Rails %>
我也有類似的功能在另一個報告控制器被用來跟蹤實際調用(不LostCalls)和它的工作原理精細。我認爲我的報告類方法存在問題,但即使出現更好的錯誤,我也很難調試它。所以總而言之,如果我擺脫LostCall.report(params[:search])
並執行`LostCall.order(「call_date ASC」)並且它將正確分頁,索引視圖將起作用。報告方法似乎被破壞並在模型中返回零。
如果我需要重構我的問題或提供更多信息,請讓我知道。我很感激您可以提供的任何幫助。
感謝和美好的一天!
更新
感謝您的反饋傢伙,我忘了初始化變量的結果。所以一個簡單的results = scoped
固定它。 :)
你說得對。我正在寫這半睡眠(不是一個好習慣),忘了初始化。所以我添加了'results = scoped'來初始化,現在事情正在工作:) – nulltek 2014-12-07 20:57:10