1

Schema:

  create_table "reports", :force => true do |t|
    t.integer  "user_id"
    t.string   "apparatus"
    t.string   "capt"
    t.text     "body"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "users", :force => true do |t|
    t.string   "login",                     :limit => 40
    t.string   "name",                      :limit => 100, :default => ""
    t.string   "email",                     :limit => 100
    t.string   "crypted_password",          :limit => 40
    t.string   "salt",                      :limit => 40
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "remember_token",            :limit => 40
    t.datetime "remember_token_expires_at"
    t.string   "rank"
    t.integer  "shift"
    t.integer  "access"
  end

user model:

Class User < ActiveRecord::Base
    has_many :reports
#   bunch of other stuff thats not important
end

report model:

Class Report < ActiveRecord::Base
    belongs_to :user
end

views/reports/index

<% @reports.each do |report| %>
  <tr>
    <td><%= report.user_id %></td>  #     ****THIS IS THE LINE IN QUESTION****
    <td><%= report.apparatus %></td>
    <td><%= report.capt %></td>
    <td><%= report.body %></td>
    <td><%= link_to 'Show', report %></td>
    <td><%= link_to 'Edit', edit_report_path(report) %></td>
    <td><%= link_to 'Destroy', report, :confirm => 'Are you sure?', :method => :delete %></td>
  </tr>
<% end %>

I would like to be able to display the name of the user that created the report. I was under the assumption that declaring the belongs_to and has_many associations would make this possible by writing report.user.name or something like that. Where have I gone wrong?

bennett_an
  • 1,718
  • 1
  • 16
  • 35
  • ok, the problem was i had one tupple in my table that didn't have a user id. so it was getting hung up trying to find the name method on nil. I'm an ass. – bennett_an Nov 03 '11 at 02:31

2 Answers2

3

I'm 99% sure it's because one or more of your reports do not have an associated user. Try

<%= report.user.name rescue "none" %>

When there is no value in user_id field on a report then report.user will return nil. So report.user.name would be like calling nil.name, which raises an error.

UPDATE: here's a better way:

<%= report.user.try(:name) %>
tybro0103
  • 48,327
  • 33
  • 144
  • 170
1

You can do:

<%= report.user.name %>

But for efficiency, in your controller you can do a join to get the users name in the same query used to fetch @reports.

This query might look something like:

@reports = Report.select("reports.id as id, reports.apparatus as apparatus, reports.capt as capt, reports.body as body, users.name as user_name").joins("LEFT JOIN `users` ON `users`.`id` = `reports`.`user_id`")

Then your output would look like:

<%= report.user_name %>
Timothy Hunkele
  • 877
  • 7
  • 15