rails: how do i access a method in my application controller?

前端 未结 4 1784
猫巷女王i
猫巷女王i 2021-02-06 01:09

Noob scoping issue, I imagine. :\\

class ApplicationController < ActionController::Base
  protect_from_forgery

  @locations = get_locations

  def get_locat         


        
4条回答
  •  滥情空心
    2021-02-06 01:47

    You're calling it from the class scope, not from an instance scope. more likely what you want is the following:

    class ApplicationController < ActionController::Base
      protect_from_forgery
      before_filter :setup_locations
    
    
      private
      def setup_locations
        @locations = Location.where(:active => true).order('name').all
      end
    
    end
    

    To make your original example work, you'd need to make #get_locations defined on self (which points to the class at definition), like so:

    class ApplicationController < ActionController::Base
      protect_from_forgery
    
      @locations = get_locations
    
      def self.get_locations
        Location.where(:active => true).order('name').all
      end
    
    end
    

    The problem with that code is that @locations will only be available from the class level as a class instance variable, which is comparable to a static variable in most other languages, and which probably isn't what you want.

提交回复
热议问题