Wednesday, 13 August 2008

The Model Part 3 - Interactive Rails Environment

Interactive Rails Environment (IRE)
You can test the methods in your model in an Interactive Rails Environment (IRE), just like IRb. Navigate to your project's root directory, and type:
ruby script/console

In this environment you can access all your models, and the development database (the other databases can be accessed by appending "test" or "production" as a parameter to the above).

When you are in the Rails interactive environment, you can invoke reload! after modifying your code to get Rails to notice the changes. However, if you have an object on the go, it will lose its methods (at least, all your methods; methods inherited from, say, ActiveRecord::Base will still be there).

Here is an example session:
>> p = Post.find :first
=> #
>> p.test
test
=> nil
>> reload!
Reloading...
=> true
>> p.test
NoMethodError: undefined method `test' for #<post:0xafcd578>
from c:/ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.0/lib/active_record/attribute_methods.rb:256:in `method_missing'
from (irb):4
>> p = Post.find :first
=> #<post>
>> p.test
test
=> nil

As can be seen above, the solution is to retrieve the object again after reload. The problem seems to be down to versions; the old object is an instance of the old version, which no longer exists.

See also:
http://www.spacevatican.org/2008/5/28/reload-me-reload-me-not
http://rpheath.com/posts/163-rails-tips-and-tricks-part-3

Struggling with Ruby: Contents Page

No comments: