简体   繁体   English

帮助程序中的Rails方法在控制台中不起作用

[英]Rails method in helper doesn't work in console

I have a method in a helper file that is pretty simple. 我在助手文件中有一个非常简单的方法。 It takes an object ( tool ) that has_many services . 它具有has_many services的对象( tool )。 Each service has a :completed date. 每个service都有一个:completed日期。 I want this method to use the built in associations to check each service . 我希望此方法使用内置的关联来检查每个service If the service.name contains the string "annual" AND the service.completed.year == DateTime.now.year , then the method should return true, else it should return false. 如果service.name包含字符串“ annual”和service.completed.year == DateTime.now.year ,则该方法应返回true,否则应返回false。 Here is my method in the tools_helper.rb file: 这是我在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 model: 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 model: 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

I can do this on the Rails console: 我可以在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

But if I do: 但是如果我这样做:

t.annual_service?

returns => false

I'm not getting an unknown method error, and if I do: 我没有收到unknown method错误,如果这样做:

t.respond_to? :annual_service

returns => true

I'm missing something simple. 我缺少一些简单的东西。 but can't seem to figure it out. 但似乎无法弄清楚。

Methods in helper module can't take effect in controller and model file automatically. 帮助程序模块中的方法不会自动在控制器和模型文件中生效。 In your view you can use helper method directly. 在您看来,您可以直接使用辅助方法。

Maybe you could include the helper module to "Tool" class and try again. 也许您可以将帮助程序模块包含在“工具”类中,然后重试。 Just like: 就像:

class Tool < ActiveRecord::Base
  include Your_Helper_Module # ToolsHelper?
  ............................

end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM