0

我使用 2 个关系表做一个应用程序,但我得到“nil:NilClass 的未定义方法‘num_letter’”

我的桌子

 index_letters:
   |id|  |num_letter|  


  letter_logs:
  |id|   |index_letter_id|

这是我的控制器

class PolicyManagement::LetterLogController < ApplicationController
   def index_document
     @letter_logs = LetterLog.find(:all)
   end
end

我的模型:

class LetterLog < ActiveRecord::Base
   belongs_to :index_letter

end

class  IndexLetter < ActiveRecord::Base
   has_many :letter_logs
end    

这是我的看法

<% @letter_logs.each do |letter_log| %>
   <%= letter_log.id %>
   <%= letter_log.index_letter.num_letter %>
<% end %> 

我试过这个

<% @letter_logs.each do |letter_log| %>
   <%= letter_log.id %>
   <%= letter_log.indexletter.num_letter %>
<% end %> 

这是我的日志

ActionView::TemplateError (undefined method `num_letter' for nil:NilClass) on line #23 of app/views/policy_management/letter_log/_table.rhtml:

新日志:

  LetterLog Columns (2.3ms)   SHOW FIELDS FROM `letter_logs`
  IndexLetter Columns (1.2ms)   SHOW FIELDS FROM `index_letters`
  IndexLetter Load (0.2ms)   SELECT * FROM `index_letters` WHERE (`index_letters`.`id` = 0) 
  CACHE (0.0ms)   SELECT * FROM `index_letters` WHERE (`index_letters`.`id` = 0) 
  CACHE (0.0ms)   SELECT * FROM `index_letters` WHERE (`index_letters`.`id` = 0) 
  CACHE (0.0ms)   SELECT * FROM `index_letters` WHERE (`index_letters`.`id` = 0) 
  CACHE (0.0ms)   SELECT * FROM `index_letters` WHERE (`index_letters`.`id` = 0) 
  CACHE (0.0ms)   SELECT * FROM `index_letters` WHERE (`index_letters`.`id` = 0) 

请问有人可以帮我吗?我将非常感谢所有帮助

4

2 回答 2

1

你没有IndexLetter分配给你LetterLog的关系。

Rails 视图中的最佳实践是在不确定对象是否存在时使用try :

<% @letter_logs.each do |letter_log| %>
   <%= letter_log.id %>
   <%= letter_log.index_letter.try(:num_letter) %>
<% end %> 

这将返回nil而不会引发错误。这是文档的摘录:

a NoMethodError exception will not be raised and nil will be returned instead, if the receiving object is a nil object or NilClass
于 2013-09-25T03:34:13.080 回答
1

试试看,如果是letter_log.index_letter.try(:num_letter),就会抛出你得到的错误。如果 a没有关联的 ,就会发生这种情况。letter_log.index_letternilletter_logindex_letter

trynil如果调用对象是 ,则方法返回nil

你的模型中还有一些奇怪的东西

class LetterLog < ActiveRecord::Base
   belongs_to :index_letter
   has_many :letter_log # the class is associated to itself without any foreign key??
end
于 2013-09-25T03:35:02.923 回答