Deutro
Deutro

Reputation: 3323

Using a before_filter in application_controller to access a model in application.html.erb leads to unexpected html

I want to access a model in my application.html.erb file. For this I defined a before_filter in the application_controller.rb:

before_filter :populate_ages

protected

def populate_ages
  @ages= Ages.all
end

In my application.html.erb I have the following:

<%= @ages.each do |age| %>
  <p><%= age.name %></p>
<% end %>

The names are rendered correctly but I get additional output which is the array @ages. It looks like this:

[#&lt;ageid: 1, name: &quot;Herren&quot;, created_at: &quot;2014-06-26 08:02:58&quot;, updated_at: &quot;2014-06-26 08:02:58&quot;&gt;, #&lt;ageid: 2, name: &quot;A-Jugend&quot;, created_at: &quot;2014-06-26 08:02:58&quot;, updated_at: &quot;2014-06-26 08:02:58&quot;&gt;, #&lt;ageid: 3, name: &quot;B-Jugend&quot;, created_at: &quot;2014-06-26 08:02:58&quot;, updated_at: &quot;2014-06-26 08:02:58&quot;&gt;]           </ul>

I have this code in a navigation bar. So my navigation bar is extended by this additional text. Adding the loop in the body leads to the same output.

Upvotes: 1

Views: 55

Answers (2)

Arup Rakshit
Arup Rakshit

Reputation: 118289

Just write as

<% @ages.each do |age| %>
  <p><%= age.name %></p>
<% end %>

@ages is an Array instance. Now Array#each returns the receiver itself, when full iteration is completed. <%=.. %> means you are telling execute the each m,method and print the result of the #each method too, which is the problem, you have faced. Thus tell your template executed the method, don't print the result of it, and to do this correct syntax is <%.. %>.

Upvotes: 1

j-dexx
j-dexx

Reputation: 10416

You don't want the = sign on the loop, change it to:

<% @ages.each do |age| %>
  <p><%= age.name %></p>
<% end %>

By having <%= @ages ... you're telling rails to display the array

Upvotes: 1

Related Questions