繁体   English   中英

rails 3 undefined方法`+'代表nil:NilClass

[英]rails 3 undefined method `+' for nil:NilClass

我在rails中制作一个排序表并收到错误。 这是我的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'

有什么问题,我该如何解决?

你的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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM