【问题标题】:rails 3 undefined method `+' for nil:NilClassrails 3 undefined method `+' for nil:NilClass
【发布时间】:2013-08-31 09:56:02
【问题描述】:

我在 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>

这是我的公司控制器

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'

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

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3.2 nomethoderror


    【解决方案1】:

    您的params[:sort] 返回nil

    您可以通过检查参数来修复它:

    @companies = Company.scoped
    if params[:sort].present? && params[:direction].present?
      @companies = @companies.order(params[:sort] + ' ' + params[:direction])
    end
    

    【讨论】:

      【解决方案2】:

      你的params[:sort]nil,所以你最好这样做:

      def index
        @companies = params[:sort].blank? || params[:direction].blank? ? Company.scoped : Company.order(params[:sort] + ' ' + params[:direction])
      end
      

      【讨论】:

      • 将抛出“未定义的方法each for nil”。
      • @badal 你有什么要求?你的看法是什么?
      • @RajarshiDas 编辑后,它仍然会抛出这个错误。事实上它什么也没改变。
      • @RajarshiDas 它应该是 scopedall 而不是 scope。现在它会抛出 wrong number of arguments 错误。
      • @RajarshiDas 还是很糟糕,顺便说一句。应该有|| 运算符而不是&amp;&amp;
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-27
      • 2020-09-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多