Search code examples
ruby-on-railsrubyruby-on-rails-3ruby-on-rails-3.2ruby-on-rails-3.1

Error getting value from tables in relationship


I doing an app using 2 tables in relationship but i'm getting "undefined method `num_letter' for nil:NilClass"

My tables

 index_letters:
   |id|  |num_letter|  


  letter_logs:
  |id|   |index_letter_id|

Here is my controller

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

My models:

class LetterLog < ActiveRecord::Base
   belongs_to :index_letter

end

class  IndexLetter < ActiveRecord::Base
   has_many :letter_logs
end    

This is my view

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

I tried this

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

This is my log

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

New logs:

  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) 

Please somebody can help me with this? I will really appreciate all help


Solution

  • Try letter_log.index_letter.try(:num_letter), the error you are getting is thrown if letter_log.index_letter is nil. This would happen if a letter_log has no associated index_letter.

    try method returns nil if the calling object is nil.

    Also something odd in your model

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