ckbrumb
ckbrumb

Reputation: 191

Rails object method returning full array

I'm having an issue with an association. I've got an Employee model that belongs_to a Role model. When I try to display the association, I get the full array displayed back.

Here's the show action from my Employee controller. As you can see, I've tried a few different methods to make the proper association in the first place:

 def show
    @employee = Employee.find(params[:id])
    # @role = Role.where(:id => @employee)
    # @role = Role.find_by_sql("select roles.role_title from roles where roles.id in (select role_id from employees where role_id='1')")
    @role = Role.where(id: @employee)
  end

And here's the view:

<p>
  <strong>Role:</strong>
  <%= @role.each do |r|
    r.role_title
    end %>
</p>

My output comes back as:

Role: [#<Role id: 3, role_title: "Support Engineer", created_at: "2014-08-20 16:09:22", updated_at: "2014-08-20 16:09:22">]

What am I missing here?

Upvotes: 0

Views: 38

Answers (2)

SteveTurczyn
SteveTurczyn

Reputation: 36860

If the employee belongs_to a role there is only one role for each employee.

You can retrieve it as easily as specifying...

@employee.role

but if you insist on constructing a separate retrieval then

@role = Role.where(id: @employee.role_id).first

EDIT

So talking about the views... if there's only one @role you don't need to iterate through an array...

<p>
  <strong>Role:</strong> <%= @role.role_title %>
</p>

You're seeing an array because the where returns an array, you could bypass that with...

@role = Role.where(id: @employee).first

As Dave Newton pointed out, if it really was an array you'd need to do...

 <p>
  <strong>Role:</strong>
  <% @role.each do |r| %>
    <%= r.role_title %>
  <% end %>
</p>

Upvotes: 1

Dave Newton
Dave Newton

Reputation: 160181

You need to actually iterate and display something for each role.

<%= %> means "display the result of the expression", which in your case, is an each.

each returns the collection you were iterating over. You want something closer to:

<% @role.each do |r| %>
  <%= r.role_title %><br/>
<% end %>

Although it obviously depends on what you actually want to display, for example:

<%= @role.collect(&:role_title).join(', ') %>

Unrelated: I might argue that Role#role_title is redundant and Role#title would be sufficient.

Upvotes: 2

Related Questions