使用控制器辅助方法时,范围值不正确

时间:2014-10-03 14:21:22

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

我试图通过我的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

当我请求该控制器的新动作时,我得到错误&#34;范围错误值#34;。

# 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,但我得到的只是一个没有数字的选择框。

1 个答案:

答案 0 :(得分: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不是一个可变对象,因此它不会像你想象的那样修改传递的param。该方法应为:

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