1

How can I get values from database in application.html.erb? I need to get those values for whole project. Those values will stay forever to all pages. How can I pass values to application.html.erb?

Is there anything like beforeRender? Is there anything like appcontroller.rb to override actions?

1

3 Answers 3

4

You could use an application wide before_filter - like so

    class ApplicationController < ActionController::Base
      before_filter :load_application_wide_varibales

      private

      def load_application_wide_varibales
        @var = Model.where :condition => "whatever"
      end
    end

@var would then be available in all your views

cheers

Sign up to request clarification or add additional context in comments.

Comments

1

you can put method in the application controller

before_filter :load_data


def load_data
 @data = Data.all
end

All controllers inherits ApplicationController, so data will be loaded at all actions. Now you can use @data at you application.html.erb file

Comments

1

The best way is probably to create a method in your application controller and declare it a helper method. Then you can call that method in application.html.erb. For example if you want to be able to use the current user throughout your application you'd do something like this:

class ApplicationController
  helper_method :current_user

  def current_user
    @current_user ||= User.find(session[:user_id])
  end
end

Then in application.html.erb you can do the following:

Hello <%= current_user.name %>

It's also possible to use before_filter like to other answers suggest, but in this solution the database only gets hit when it's necessary. With before_filter it always gets hit.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.