rails 3 неопределенный метод `+'для nil:NilClass
Я делаю таблицу сортировки в рельсах и получаю ошибку. Это мой index.html.erb
<table>
<tr>
<th><%= sortable "name" %></th>
<th><%= sortable "city" %></th>
<th><%= sortable "country" %></th>
<th><%= sortable "street_address" %></th>
<th><%= sortable "sector" %></th>
<th><%= sortable "telephone" %></th>
<th><%= sortable "fax" %></th>
</tr>
<% for company in @companies %>
<tr>
<td><%= company.name %></td>
<td><%= company.city %></td>
<td><%= company.country %></td>
<td><%= company.street_address %></td>
<td><%= company.sector %></td>
<td><%= company.telephone %></td>
<td><%= company.fax %></td>
</tr>
<% end %>
</table>
Это мой companies_controller
def index
@companies = Company.order(params[:sort] + ' ' + params[:direction])
end
Это мой application_helper
def sortable(column, title = nil)
title ||= column.titleize
direction = (column == params[:sort] && params[:direction] == "asc") ? "desc" : "asc"
link_to title, :sort => column, :direction => direction
end
И ошибка:
NoMethodError in CompaniesController#index
undefined method `+' for nil:NilClass
app/controllers/companies_controller.rb:21:in `index'
В чем проблема и как я могу это исправить?
2 ответа
Решение
Ваш params[:sort]
возвращается nil
,
Вы можете исправить это, например, проверив свои параметры:
@companies = Company.scoped
if params[:sort].present? && params[:direction].present?
@companies = @companies.order(params[:sort] + ' ' + params[:direction])
end
Ваш params[:sort]
является nil
так что вам лучше сделать:
def index
@companies = params[:sort].blank? || params[:direction].blank? ? Company.scoped : Company.order(params[:sort] + ' ' + params[:direction])
end