我在帮助文件中有一个非常简单的方法。它需要一个对象(tool
)has_many services
。每个service
都有一个:completed
日期。我希望此方法使用内置关联来检查每个service
。如果service.name
包含字符串“annual”和service.completed.year == DateTime.now.year
,则该方法应返回true,否则返回false。这是我在tools_helper.rb文件中的方法:
def annual_service?
self.services.each do |service|
if (service.name =~ /annual/) && (service.completed.year == DateTime.now.year)
return true
end
end
end
Too.rb模型:
class Tool < ActiveRecord::Base
has_many :repairs
has_many :services
has_many :expended_parts, through: :services
has_many :service_types, through: :services
belongs_to :category
belongs_to :location
accepts_nested_attributes_for :repairs
accepts_nested_attributes_for :services
validates :serial, :uniqueness => true
validates :serial, :presence => true
end
Service.rb模型:
class Service < ActiveRecord::Base
before_destroy :replace_parts
belongs_to :tool
belongs_to :service_type
has_many :expended_parts, dependent: :destroy
has_many :parts, through: :expended_parts
after_create :withdraw_parts
default_scope order('due_date DESC')
end
我可以在Rails控制台上执行此操作:
t = Tool.find(16)
t.services.each do |service|
if (service.name =~ /annual/) && (service.completed.year == DateTime.now.year)
puts "true"
end
end
returns => true
但如果我这样做:
t.annual_service?
returns => false
我没有收到unknown method
错误,如果我这样做:
t.respond_to? :annual_service
returns => true
我错过了一些简单的事情。但似乎无法弄清楚。
答案 0 :(得分:0)
辅助模块中的方法不能自动在控制器和模型文件中生效。在您的视图中,您可以直接使用帮助方法。
也许您可以将帮助程序模块包含在“工具”类中,然后重试。就像:
class Tool < ActiveRecord::Base
include Your_Helper_Module # ToolsHelper?
............................
end