如果總是用一個模型中我把它放在模型。你的方法名前self.
意味着它是一個類的方法,所以如果你這樣定義方法:
class Milestone < ActiveRecord::Base
def self.number_of_months(start_date,to_date)
# Get how many months you want to view from the start months
(to_date.month - start_date.month) + (to_date.year - start_date.year) * 12 + 1
end
end
你會做這樣使用它:
Milestone.number_of_months(date1,date2)
或者你可能想把它放在config/initializers
目錄中。例如,在包含目錄下創建一個名爲date.rb
文件:
class Date
def self.number_of_months(start_date,to_date)
# Get how many months you want to view from the start months
(to_date.month - start_date.month) + (to_date.year - start_date.year) * 12 + 1
end
end
這將作爲一類方法Date類。
我注意到你提到的方法需要在控制器和模型中使用的第一個答案。助手用於觀點,這可能不會對你有所幫助。
這應該是一個輔助方法。每個控制器都有一個輔助模塊,但也有一個應用範圍的模塊。該方法很好放在那裏,只要確保它不是一個類方法(刪除self.
)。如果您不想將該方法添加到應用程序幫助程序中,則可以在控制器中使用helper
聲明以及它所屬的幫助程序模塊,即如果方法在date_range_helper.rb
中,則使用helper :date_range
。