架构:
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
用户模型:
Class User < ActiveRecord::Base
has_many :reports
# bunch of other stuff thats not important
end
报告模型:
Class Report < ActiveRecord::Base
belongs_to :user
end
视图/报告/索引
<% @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 %>
我希望能够显示创建报告的用户的名称。我假设声明belongs_to和has_many关联可以通过编写report.user.name或类似的东西来实现这一点。我哪里出错?
答案 0 :(得分:3)
我99%肯定是因为您的一个或多个报告没有相关用户。尝试
<%= report.user.name rescue "none" %>
如果报告中的user_id字段中没有值,则report.user
将返回nil。所以report.user.name
就像调用nil.name
一样,这会引发错误。
更新:这是一个更好的方法:
<%= report.user.try(:name) %>
答案 1 :(得分:1)
你可以这样做:
<%= report.user.name %>
但是为了提高效率,您可以在控制器中进行连接,以获取用于获取@reports的同一查询中的用户名。
此查询可能类似于:
@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`")
然后你的输出看起来像:
<%= report.user_name %>