# Undefind local variable error

**URL:** <https://www.ruby-forum.com/t/undefind-local-variable-error/108440>\
**Category:** Rails\
**Created:** [July 3, 2007, 4:26pm UTC](https://www.ruby-forum.com/t/undefind-local-variable-error/108440 "2007-07-03T16:26:30Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![jfjfjf](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/3d9bf3/32.png) [@jfjfjf](https://www.ruby-forum.com/u/jfjfjf)\
**Post date:** [July 3, 2007, 4:26pm UTC](https://www.ruby-forum.com/t/undefind-local-variable-error/108440/1 "2007-07-03T16:26:30Z")

</div>

I’m getting the following error when I run this line in the console:

History.find\_ec\_id(770893)  
NameError: undefined local variable or method `target\_history’ for  
History:Class

I have the following methods in my History model. I don’t understand  
why this doesn’t work. There is definitely a history with a route\_id of  
40 and a so\_number of 770893 in the db. Any ideas on what I’m doing  
wrong here, or how I could do this better? Thanks!

def self.find\_ec\_history(so\_number)  
histories = History.find(:all, :conditions =\> [‘so\_number =  
?’,so\_number], :order =\> ‘timestamp desc’)

histories.each { |his|  
if his.is\_ec?  
target\_history = his  
break  
end  
}

```
return target_history

```

end

def is\_ec?  
return route\_id == 40  
end

---

<div class="post-metadata">

**Author:** ![jfjfjf](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/3d9bf3/32.png) [@jfjfjf](https://www.ruby-forum.com/u/jfjfjf)\
**Post date:** [July 3, 2007, 4:33pm UTC](https://www.ruby-forum.com/t/undefind-local-variable-error/108440/2 "2007-07-03T16:33:24Z")

</div>

Whoops! I meant I ran the following in the console:

History.find\_ec\_history(770893)

---

<div class="post-metadata">

**Author:** ![jfjfjf](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/3d9bf3/32.png) [@jfjfjf](https://www.ruby-forum.com/u/jfjfjf)\
**Post date:** [July 3, 2007, 4:33pm UTC](https://www.ruby-forum.com/t/undefind-local-variable-error/108440/3 "2007-07-03T16:33:41Z")

</div>

jf wrote:

> ```
> return target_history
> 
> ```
> 
> end
> 
> def is\_ec?  
> return route\_id == 40  
> end

target\_history is local to it’s original containing block. Define it  
ahead of time and you should be good to go.

target\_history = nil  
histories.each { |his|  
if his.is\_ec?  
target\_history = his  
break  
end  
}

return target\_history

–  
[http://www.5valleys.com/](http://www.5valleys.com/)

---

<div class="post-metadata">

**Author:** ![jfjfjf](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/3d9bf3/32.png) [@jfjfjf](https://www.ruby-forum.com/u/jfjfjf)\
**Post date:** [July 3, 2007, 4:47pm UTC](https://www.ruby-forum.com/t/undefind-local-variable-error/108440/4 "2007-07-03T16:47:20Z")

</div>

You’re right!

Thanks so much for your help!
