Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to define Rails variable in application.html.erb

I have a navbar that is placed in the /views/layouts/application.html.erb and in there I place the @buy and @sell variables which get the latest bitcoin price. They are currently placed in the /welcome controller so the prices only show when in the welcome controller. If I navigate to another controller, the bar just becomes empty.

@buy = coinbase.buy_price
@sell = coinbase.sell_price

That is the code that is currently placed in the welcome controller. I want it to be available to the navbar regardless of what controller the user is in. Any help would be great!

like image 689
user3024194 Avatar asked Oct 24 '25 02:10

user3024194


2 Answers

place it in the application controller and use a before action

before_action :set_prices
def set_prices
    @buy = coinbase.buy_price
    @sell = coinbase.sell_price
end
like image 60
pcarvalho Avatar answered Oct 25 '25 15:10

pcarvalho


Two ways:

  1. Write the code in application_controller as before_filter, and use the variables in nav bar.

    before_filter :prices

    def prices

    @buy = coinbase.buy_price

    @sell = coinbase.sell_price

    end

  2. Write the code in application.html.erb, just before the nav bar code:

    <% @buy = coinbase.buy_price %>

    <% @sell = coinbase.sell_price %>

    And use them directly.

like image 32
Max Wong Avatar answered Oct 25 '25 16:10

Max Wong