【问题标题】:Bad value for range when using a controller helper method使用控制器辅助方法时范围值错误
【发布时间】:2014-11-28 14:51:19
【问题描述】:

我正在尝试通过我的 ActionController 运行一个辅助方法,如下所示。

# app/controllers/application_controller.rb

class ApplicationController < ActionController::Base
  def set_count(object_count, class_name)
    ["new", "create"].include? action_name ? object_count = class_name.count + 1 : object_count = class_name.count
    end
end

当我请求该控制器的新操作时,我收到错误“范围值错误”。

# app/views/subjects/new.html.erb

<%= form_for @subject do |f| %>
  <table summary="Subject form field">
    <tr>
        <th><%= f.label :position %></th>
        <td><%= f.select :position, 1..@subject_count %></td>
    </tr>
  </table>
<% end %>

请记住,如果我将它放在控制器本身中,此方法有效:

# app/controllers/subjects.rb

def set_count
  ["new", "create"].include? action_name ? @subject_count = Subject.count + 1 : @subject_count = Subject.count
end

按如下方式运行:

before_action :set_count, only: [:new, :create, :edit, :update]

我更愿意将它作为助手,因为其他几个控制器使用与此类似的东西。我尝试使用 to_i 将范围转换为 Fixnum,但我得到的只是一个没有数字的选择框。

【问题讨论】:

    标签: ruby-on-rails ruby methods controller helper


    【解决方案1】:

    试试:

    ["new", "create"].include?(action_name) ? object_count = class_name.count + 1 : object_count = class_name.count
    

    这里非常需要这些括号。否则 ruby​​ 解析器会将其解释为:

    ["new", "create"].include? (action_name ? object_count = class_name.count + 1 : object_count = class_name.count)
    

    这将返回 truefalse。 (嗯,总是false

    另外,您不能修改传递给方法的 fixnum 值:

    def set_count(object_count, class_name)
      ["new", "create"].include? action_name ? object_count = class_name.count + 1 : object_count = class_name.count
    end
    

    object_count 在这里是一个局部变量,而 Fixnum 不是一个可变对象,因此它不会像您预期的那样修改传递的参数。此方法应为:

    def get_count(klass)
      ["new", "create"].include?(action_name) ? klass.count + 1 : klass.count
    end
    

    然后在你看来:

    <td><%= f.select :position, 1..get_count(Subject) %></td>
    

    记住这个方法需要移动到辅助模块,或者需要标记为辅助方法:

    class SomeController < AplicationController
      helper_method: :get_count
    end
    

    【讨论】:

    • 括号似乎没有做任何事情。仍然出现该错误。
    • @CarlEdwards - 更新答案。
    • 由于某种原因,当我使用 get_count 方法和代码来获取 wrong number of arguments (0 for 1) 的视图时,我应该同时使用 set_countget_count 吗?
    • 好的,我想我可能已经解决了上述问题。问题是将方法从我的ApplicationController 文件中移出到ApplicationHelper。还删除了 before_action,因为它不再需要。谢谢!
    • 您介意在您的回答中提及将get_count 方法移至ApplicationHelper 以便我可以将其标记为正确吗?我将更新我的问题以指示代码最初的位置。乍一看,其他人可能会感到困惑。
    猜你喜欢
    • 1970-01-01
    • 2021-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-13
    • 1970-01-01
    • 1970-01-01
    • 2011-02-05
    相关资源
    最近更新 更多