【问题标题】:Rails 4 error: The scope body needs to be callableRails 4错误:范围主体需要可调用
【发布时间】:2016-01-03 05:57:25
【问题描述】:

我正在尝试在 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.

如何使范围“可调用”?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 activerecord scope


    【解决方案1】:

    根据错误消息,作用域的主体需要包含在可调用的对象中,例如 ProcLambda。像这样:

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

    这样可以确保每次使用范围时都会评估块的内容。

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

    【讨论】:

    • 非常感谢。当错误消息是为更了解预期内容的人编写的时,很难从错误消息中提取这些信息。
    猜你喜欢
    • 2015-05-11
    • 1970-01-01
    • 2016-10-17
    • 2011-12-07
    • 1970-01-01
    • 2016-07-11
    • 2016-08-23
    • 2017-09-16
    • 1970-01-01
    相关资源
    最近更新 更多