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

前端 未结 4 1787
猫巷女王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条回答
  •  梦毁少年i
    2021-02-06 01:29

    You're calling get_locations within the class scope, but the method is an instance method, not a class method. If for example you used def self.get_locations then you would be providing a class method, one of which you can use within the class scope (after you have defined it, not before like you're doing).

    The problem here is the logic, what is this method for? What do you intend to use @locations for? If it's to go inside your application view, then you should put this method into the ApplicationHelper module, and call it from inside the relevant action. If you'd like it in another view on another controller and you'd like to use @locations inside your locations method, perhaps your setup might look something like this:

    PagesController

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

    locations.html.erb

    <% @locations.each do |location| %>
      <%= # do something with 'location' %>
    <% end %>
    

    If you'd like to use this inside of your application.html.erb you can simplify it quite some..

    ApplicationController

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

    application.html.erb

    <% locations.each do |location| %>
      <%= # do something with location %>
    <% end %>
    

    The answer boils down to logic, and to really figure out exactly what you're looking for, more details would probably be required.

提交回复
热议问题