[Rails] Using an unsaved object

Eric Anderson eric at afaik.us
Tue Jan 18 23:14:18 GMT 2005


I have a view that will allow me to edit an object. If I load up the 
edit action it displays the current info for the object in the fields 
fine. When I try to create a new object I use the same view as for the 
edit action. The difference is how I create the object which is 
providing the defaults in the HTML interface. So the following is some 
snippets out of my user_controller.rb file (a user object is the object 
I am creating).

def new
	@usr = User.new
	render_action 'edit'
end

def edit
	@usr = User.find_by_username @params['id']
end

My view has the following snippet in it when trying to display the 
username to the screen:

<input type="text" name="username" value="<%=@usr.username%>" />

This works fine with I edit a user, but when I go to add a new user I 
get the following:

ActionView::TemplateError (undefined method `include?' for nil:NilClass) 
on line #4 of /user/edit.rhtml:

Of course there is no "include?" on line #4 (which is the HTML line 
above). So I look at the backtrace and see the last stackframe has:

/www/../config/..//vendor/activerecord/lib/active_record/base.rb:961:in 
`method_missing'

So I look at line 961 of base.rb in ActiveRecord and I see the following:

if method_name =~ read_method? && @attributes.include?($1)
   return read_attribute($1)

So we can obviously see where the "include?" is now. My problem is why 
is @attributes equal to nil? According to initialize this should not 
happen even if we are creating a new object:

def initialize(attributes = nil)
   @attributes = attributes_from_column_definition
   @new_record = true
   ensure_proper_type
   self.attributes = attributes unless attributes.nil?
   yield self if block_given?
end

So how can it be nil? My goal is to have the same "view" for both edit 
and new. The difference is that the new will consist of all blanks and 
the "edit" will have real values in the data object, but the view will 
not care one way or another. It is just displaying the info in the data 
object.

Any suggestions?

Thanks,

Eric
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 187 bytes
Desc: OpenPGP digital signature
Url : http://one.textdrive.com/pipermail/rails/attachments/20050118/eb8e9495/signature.bin


More information about the Rails mailing list