Finnjon
Finnjon

Reputation: 671

Iterate over an Active Record Relation in Rails 3.2

I have the following code:

@items = QuestionGroup.search(params[:search]).limit(50)

This returns an ActiveRecord relation. In the view I want to iterate through it so I use:

<% if @items.present? %>
    <%= @items.each do |r| %>
        <%= div_for r do %>
            <div><%= r.subject %></div>
        <% end %>
    <% end %>
<% end %>

This does print r.subject to the view but it then follows it with the entire relation. e.g.

the pipe
[#<QuestionGroup id: **, subject: "the pipe", created_at: "*******", updated_at: "******"]

Why is this and how can I fix it?

Upvotes: 1

Views: 2159

Answers (1)

Philipp Meissner
Philipp Meissner

Reputation: 5482

Problem is here:

<%= @items.each do |r| %>

This line of code iterates over each of the relations and due to the '=' you output its content. Change it to:

<% @items.each do |r| %>

and you are good to go!

Upvotes: 1

Related Questions