Rails模型/连接表无法正常工作

时间:2014-02-20 18:52:26

标签: ruby-on-rails ruby

我正在尝试通过创建新的连接表“LastViewer”来加入两个预先存在的表“Report”和“Person”。基本上,查看器表将跟踪上次查看报告的人。

我创建了一个Rails模型,创建了一个文件“last_viewer.rb”,如下所示:

class LastViewer < ActiveRecord::Base
  belongs_to :report
  belongs_to :person
end

这会产生以下迁移:

class CreateLastViewers < ActiveRecord::Migration
  def change
    create_table :last_viewers do |t|
      t.references :person
      t.references :report

      t.timestamps
    end
    add_index :last_viewers, :person_id
    add_index :last_viewers, :report_id
  end
end

现在,我开始添加代码,以便我的应用程序可以跟踪更改。我将以下内容添加到正确的控制器中:

@viewer = LastViewer.new
@viewer.person_id = get_current_user[:id] # correctly gets the person's ID from the correct session
@viewer.report_id = @report.id
@viewer.save

现在,我希望显示最后一个查看器,我添加了:

<% @reports.each_with_index do |report,index| %>
  <% query = LastViewer.where(:report_id => report.id).last %>
  <% name = query.person.name || "No Person found" %>
  <% time = Format.to_time(query.created_at.localtime) %>
<% end %>

我得到的错误是:

nil的未定义方法`name':NilClass

就行了

  <% name = query.person.name || "No Person found" %

编辑:

Person模型的相应部分:

class Person< ActiveRecord::Base
  attr_accessible :hid, :name, :email, :cell, :display
  has_many :last_viewer
end

报告模型的相应部分:

class Report< ActiveRecord::Base
  has_many :last_viewer
end

2 个答案:

答案 0 :(得分:2)

query.person是零。您可以使用try来阻止错误:

<% name = query.person.try(:name) || "No Person found" %>

答案 1 :(得分:1)

首先,您需要将关系更改为:( has_many :last_viewers上的复数)

class Person < ActiveRecord::Base
  has_many :last_viewers


class Report < ActiveRecord::Base
  has_many :last_viewers

class LastViewer < ActiveRecord::Base
  belongs_to :report
  belongs_to :person
  validates :report_id, :person_id, presence: true

然后,尝试强制创建LastViewer对象,引发错误并查看对象有什么问题:

@viewer = LastViewer.new
@viewer.person_id = get_current_user[:id]
@viewer.report_id = @report.id
@viewer.save! # adding a ! will raise errors if object not valid

# one-line equivalent:
@viewer = LastViewer.create!(person_id: get_current_user[:id], report_id: @report.id)

我很确定会出现像“person_id不应该是空白”这样的错误。我认为你的方法get_current_user[:id]不会返回id。

解决此问题后,我建议您将视图重构为:

<% @reports.each_with_index do |report, index| %>
  <% last_viewer = report.last_viewers.last %>
  <% last_person_name = last_viewer.try(:person).try(:name) %>
  <% time = Format.to_time(query.created_at.localtime) %>
<% end %>