2014-10-03 47 views
0

我想通過我的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, [email protected]_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

嘗試:

["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 
+0

它看起來不像圓括號做任何事情。仍然收到該錯誤。 – 2014-10-03 14:27:03

+0

@CarlEdwards - 更新了答案。 – BroiSatse 2014-10-03 14:28:45

+0

出於某種原因,當我使用'get_count'方法和視圖代碼時,我得到'錯誤的參數數量(0代表1)'我應該同時使用'set_count'和'get_count'嗎? – 2014-10-03 14:35:25

相關問題