0

I created a method in app/helpers/logs_helper.rb:

def product_name(id)
  Product.find_by_id(id).name
end

I want to use this product_name in app/helpers/logs_helper/products_log_helper.rb:

module LogsHelper
  module ProductsLogHelper
    def search(params)
      product_log_name = product_name(params[:id])
    end
  end
end

But it can't find product_name even I use:

include LogsHelper

in the products_log_helper.rb file.

How to do this? I am using Rails 3.2

Martin Tournoij
  • 26,737
  • 24
  • 105
  • 146
j-zhang
  • 693
  • 1
  • 8
  • 17

1 Answers1

2

A helper method is visible to the views (and by extension the controller); they're not really a place to put "general purpose functions", but rather functions for your views.

What you probably want to do, is probably make an app/classes/log.rb:

class Log
  def self.product_name id
    Product.find_by_id(id).name
  end
end

After which you can use this everywhere in your Rails app:

Log.product_name 42

You could also get a controller instance, but this is hacky:

helpers = ApplicationController.new.view_context
helpers.product_name 42

I'm not sure what you're trying to do here, but this method could also be on your model::

class Product < ActiveRecord::Base
  # ...

  def self.get_name_by_id id
    self.find_by_id(id).name
  end
end

After which you can just use:

Product.get_name_by_id 42
Martin Tournoij
  • 26,737
  • 24
  • 105
  • 146
  • I agree with this other than, it's been convention to use `lib/my_mclass` - see [here](http://stackoverflow.com/questions/3356742/best-way-to-load-module-class-from-lib-folder-in-rails-3) – Anthony Dec 12 '14 at 02:12
  • @Anthony The downside of the `/lib` directory is that you need to reload the entire rails app when you change a file there (unless you configure Rails to do something different), which is not the case with `/app/classes` (or any other subdirectory in `/app/`). – Martin Tournoij Dec 12 '14 at 02:16
  • Thank you very much. You give me three good methods! Learned some good practices! – j-zhang Dec 12 '14 at 02:24