kalahari
kalahari

Reputation: 974

Rails 3 in table where statement doesn't work

I am trying to render some information through a table which includes Users and in that table I want a column named Company (for each of users). In user.rb there is a column named company_id and this is the link between Company model and User model. Now, this is the index.html.erb:

<% provide(:title, 'Non-developers') %>
<h1>Non - developers</h1>

<table class="pretty" border="1" cellpadding="10">  
  <tr>
    <th></th>
    <th><%= sortable "name" %></th>
    <th><%= sortable "email" %></th>
    <th><%= sortable "company_id" %></th>
    <th>DELETE</th>
  </tr>  

  <% for user in @users %>  
  <tr class="<%= cycle('oddrow', 'evenrow') -%>">
    <td><%= gravatar_for user %></td>
    <td><%= link_to user.name, user %></td>
    <td><%= user.email %></td>
    <% company = Company.where(:id => user.company_id) %>
    <td><%= company.name %></td>
    <td><% if current_user.admin? || ( ( current_user.developer? && !current_user?(user) ) && (user.boss_id == current_user.id) ) %>
      || <%= link_to "delete", user, method: :delete,
                              data: { confirm: "You sure?" } %>
        <% end %></td>
  </tr>
  <% end %>
</table>
<%= will_paginate @users %>

This part

<% company = Company.where(:id => user.company_id) %>
<td><%= company.name %></td>

does not work and always returns "Company" word. How can I see each user's actual company name?

Upvotes: 0

Views: 186

Answers (2)

mithyavadini
mithyavadini

Reputation: 11

The statement Company.where(:id => user.company_id) will give return you an object of type ActiveRecord::Relation and such an object may have many records in it since it is basically the result of an SQL query. You should use <td><%= user.company.name %></td> in stead, if name is a column or attribute for Company.

Hope that helps!

Upvotes: 1

Arjan
Arjan

Reputation: 6274

where returns a collection of companies, rather than a single company. Try

<% company = Company.find(user.company_id) %>

Or better yet:

<% company = user.company %>

This requires you to have a belongs_to :company association in your User model.

Upvotes: 2

Related Questions