NoMethodError when trying to invoke helper method from Rails controller

前端 未结 14 1202
滥情空心
滥情空心 2020-11-30 20:05

I\'m getting a NoMethodError when trying to access a method defined in one of my helper modules from one of my controller classes. My Rails application uses the

14条回答
  •  感情败类
    2020-11-30 20:47

    If you only have ApplicationHelper inside your app/helpers folder than you have to load it in your controller with include ApplicationHelper. By default Rails only load the helper module that has the same name as your controller. (e.g. ArticlesController will load ArticlesHelper). If you have many models (e.g. Articles; Posts; Categories) than you have to upload each one in you controller. the docs

    Helper

    module PostsHelper
        def find_category(number)
            return 'kayak-#{number}'
        end
        def find_other_sport(number)
            "basketball" #specifying 'return' is optional in ruby
        end
    end
    
    module ApplicationHelper
        def check_this_sentence
            'hello world'
        end
    
    end
    

    Example Controller

    class ArticlesController < ApplicationController
        include ApplicationHelper
        include PostsHelper
        #...and so on...
    
      def show#rails 4.1.5
        #here I'm using the helper from PostsHelper to use in a Breadcrumb for the view
        add_breadcrumb find_other_sport(@articles.type_activite), articles_path, :title => "Back to the Index"
        #add_breadcrumb is from a gem ... 
        respond_with(@articles)
      end
    end
    

提交回复
热议问题