Rails中的外键关联出错

时间:2017-08-17 19:01:20

标签: ruby-on-rails ruby-on-rails-4 activerecord

我有两种模式:

user.rb

class User < ActiveRecord::Base
  ...
  has_many :reports, :foreign_key => "assigned_user_id"
  ...
end

report.rb

class Report < ActiveRecord::Base
  belongs_to :assigned_user, :class_name => "User"
end

索引操作

def index
  @all_reports = Report.all
end

index.html.erb

<% @all_reports.each do |report| %>
  <%= report.user.email %> </br>
<% end %>

这会引发错误:

undefined method `user' for #<Report:0x007f90dc642e80>

我错过了什么?我的其他 - 标准轨道 - 协会工作完美。

1 个答案:

答案 0 :(得分:4)

更改此行:

<%= report.user.email %> </br>

要:

<%= report.assigned_user.email %> </br>