从关系中的表中获取值时出错

时间:2013-09-25 03:22:31

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-3.2 ruby-on-rails-3.1

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

我的桌子

 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) 

请有人帮我这个吗?我将非常感谢所有的帮助

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

尝试letter_log.index_letter.try(:num_letter),如果letter_log.index_letternil,则会引发错误。如果letter_log没有关联index_letter,则会发生这种情况。

如果调用对象为try,则

nil方法返回nil

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

class LetterLog < ActiveRecord::Base
   belongs_to :index_letter
   has_many :letter_log # the class is associated to itself without any foreign key??
end