简体   繁体   中英

Rails4 about helper_method

I have question about helper_method .

When I add fuc in /controller/application_controller.rb

helper_method :values

def values
  @food = Food.all
  @food_type = FoodType.all
end

I want to use var on /layouts/application.html.erb

code here

<% @food.each do |fp|%>
  <p><%= fp.name %></p>
<% end %>

<% @food_type.each do |ft|%>
  <p><%= ft.name %></p>
<% end %>

but it return nill .

Please teach me ,thx a lot

You can try this

application_controller.rb

def values
  @food = Food.all
  @food_type = FoodType.all
  [@food, @food_type]
end

application.html.erb

<%food, food_type = values%>
<% food.each do |fp|%>
<p><%= fp.name %></p>
<% end %>

<% food_type.each do |ft|%>
<p><%= ft.name %></p>
<% end %>

DRY

You'll be much better using the before_action callback

The problem you have is a helper is meant as a simple way to create functionality for your application. IE that you pass some data to the helper, it will "crunch" the data, and return a reasonable response.

This is why Vimsha 's answer has been accepted - he has made it so that your helper method will return the values you need; consequently meaning you need to call the method if you want to use the data it has .

--

The real answer for you (considering you just want to be able to use the @food and @food_type variables in your application layout), is to use a callback which sets these variables each time:

#app/controllers/application_controller.rb
Class ApplicationController < ActionController::Base
   before_action :set_vars

   private

   def set_vars
      @food = Food.all
      @food_type = FoodType.all
   end
end

Although relatively inefficient (you'll be best caching this data so it won't be pinging your DB each time), you'll be able to use @food and @food_type in your application layout with no issues

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM