raviture
raviture

Reputation: 1059

Need to store query result instead of storing query in ActiveRecord

I am having following function to find some of the selected records from public pages.

    def find_public_page(title)
      @footer_public_pages ||= PublicPage.where(title: %w(welcome_to_toylist terms_of_services buying_a_toy selling_a_toy requesting_a_toy ad_guildelines))
      @footer_public_pages.find_by(title: title)
    end

what I need is that @footer_public_pages should store the result set in first time and then on next time it will directly hit the find_by query instead of firing two queries.

Any help would be appreciated.

Upvotes: 0

Views: 598

Answers (2)

Amit Sharma
Amit Sharma

Reputation: 3477

You can try this. I hope this will help You.

def find_public_page(title)
  @footer_public_pages ||= PublicPage.where(title: %w(welcome_to_toylist terms_of_services buying_a_toy selling_a_toy requesting_a_toy ad_guildelines)).group_by(&:title)
  @footer_public_pages[title].first unless @footer_public_pages[title].blank?
end

Upvotes: 1

ConnorCMcKee
ConnorCMcKee

Reputation: 1645

The instance variable @footer_public_pages belongs to a class, in this case probably the controller. Because of the way the controller works, every action (i.e. redirect) is going to be a new instance, and will need to set that value again on calling find_public_page. The way it's currently coded would help you if you were calling the method multiple times in the same action (and/or its views), but I doubt that is the case. Instead, if you're trying to keep this variable across multiple pages, you'll want to use a session variable. So you could say:

def find_public_page(title)
  session[:footer_public_pages] ||= PublicPage.where(title: %w(welcome_to_toylist terms_of_services buying_a_toy selling_a_toy requesting_a_toy ad_guildelines))
  session[:footer_public_pages].find_by(title: title)
end

If you follow this approach, just be warned that these session variables will only be dumped when the user closes the browser (NOT when they navigate away from your site), so you have to be careful in managing them.

Upvotes: 0

Related Questions