0

I have a Rails 5 web app (almost). I want to include an attribute on all my views. I read somewhere that the way to do this was to define a helper method in my application controller, so I defined

class ApplicationController < ActionController::Base

  before_action :store_last_page_visited

  protect_from_forgery with: :exception

  helper_method :unvoted_people
    ...

    def unvoted_people
      @unvoted_people = People.find_most_voted(current_user)
    end

I only have an application layout for all my pages, yet in my view the logic after

<% if @unvoted_people %>

never gets called, even though I know the query should return results. What's the right way to include a model attribute that all my views can access?

tereško
  • 56,151
  • 24
  • 92
  • 147

1 Answers1

1

you should be calling unvoted_people the helper method you defined in the application_controller, you can get rid of the instance variable and return it from the unvoted_people method.

Subash
  • 2,956
  • 5
  • 26
  • 41
  • Ok that seems to work. But I have a follow up question. Right after my "" line, I have a "" line taht iterates over the results. Am I repeatedly calling the method? How do I only invoke the method once and use its result multiple times? –  Feb 01 '18 at 00:03
  • 1
    `@unvoted_people ||= People.find_most_voted(current_user)` – Brad Werth Feb 01 '18 at 00:14
  • @Natalia yes you can use Brad's suggestion to cache those results so you don't end hitting the database on every call of the method – Subash Feb 01 '18 at 00:26
  • Thanks and just so I'm clear, where does the "@unvoted_people ||= People.find_most_voted(current_user)" line belong, is that the body of my helper method? –  Feb 01 '18 at 14:54
  • @Natalia Yes exactly – Subash Feb 02 '18 at 06:26