Rails4错误:作用域主体需要是可调用的



我正在尝试在Rails 4中制作一个应用程序。

我有一个行业模型。

我正在尝试制作一个行业索引,并按字母顺序列出。

我有一个行业.rb与:

  scope :alphabetically, order("sector ASC")

我有一个索引控制器:

  def index
    @industries = Industry.alphabetically
  end

在我的索引视图中,我有:

<% @industries.each do |industry| %>            
          <tr>
            <td><%= image_tag industry.icon.tiny.url %></td>
            <td><%= industry.sector %></td> 
            <td><%= link_to 'Show', industry %></td>
            <td><%= link_to 'Edit', edit_industry_path(industry) %></td>
            <td><%= link_to 'Destroy', industry, method: :delete, data: { confirm: 'Are you sure?' } %></td>
          </tr>
         <% end %> 

当我尝试这个,我得到这个错误:

ArgumentError in IndustriesController#index
The scope body needs to be callable.

如何使作用域"可调用"?

根据错误消息,作用域的主体需要封装在可调用的东西中,比如Proc或Lambda。像这样:

scope :alphabetically, -> {
  order("sector ASC")
}

这样可以确保每次使用作用域时都对块的内容进行评估。

因此,如果您如上所示更改您的范围,它应该会起作用并解决您的问题。

最新更新