0

In my Rails application I have this:

class ProjectsController < ApplicationController

  include ApplicationHelper

  def index
    @payments = current_user.projects.custom_order
  end

  ...

end

module ApplicationHelper

  def custom_order 
    order("name ASC")
  end

end

However, in my index view I get this error:

undefined method 'custom_order' for #<Class:0x007f8be606ff80>

How can this be done?

I would like to keep the custom_order method in a helper module because I am using it across various different controllers.

Thanks for any help.

Tintin81
  • 9,821
  • 20
  • 85
  • 178
  • Okay . Just realized that it won't work. You cannot make order in helper method. As when you are doing .projects ... Then class is activerecords of class Project. Which is a model. Unless you use scope you cannot order any active record. – Pankhuri Kaushik Dec 04 '13 at 19:54
  • Try to extend active record base class to add custom order method . http://stackoverflow.com/questions/2328984/rails-extending-activerecordbase. Refer this .. http://stackoverflow.com/questions/2328984/rails-extending-activerecordbase – Pankhuri Kaushik Dec 04 '13 at 20:01

3 Answers3

1

I know what you mean, but the right way is use model scopes:

class Project < ActiveRecord::Base
  #...

  scope :custom_order, order('name ASC')

  #...
end
NARKOZ
  • 27,203
  • 7
  • 68
  • 90
  • Thanks but my intention is to use that scope across various different controllers. And to be honest my `custom_order` method is a bit more dynamic than the one I posted above for reasons of brevity. – Tintin81 Dec 04 '13 at 19:41
  • You can use that scope across various different controllers. – NARKOZ Dec 04 '13 at 19:50
0

Move it to application controller.and make it a helper method.

Or include application helper module in application controller. So you will be able to access all application helper methods in all controllers.

0

Normally View Helpers are meant for rendering html based outputs, There you couldn't expect your model based queries.

Once you write a helper method in Application helper, It can be called in Any views.

Change your query like this

@payments = current_user.projects.order("name")

Or otherwise In your model Make it with scope.

scope :custom_order, order('name ASC')
Thamizh
  • 1
  • 1