Sunday, September 10, 2006

Rails and the initialize() method

I spent a bit of time this weekend on a pet rails project. I came across a strange error when trying to create new records through the application. Editing was working just fine, but creating a new record just seemed to hang.

Breakpoints came to my rescue. In Ruby, they're really handy. You can put a 'breakpoint' call anywhere in your code, and if you have a breakpointer process running (start this with the command 'ruby script/breakpointer'), you jump straight into an interactive ruby console debug session when the breakpoint is hit.

Using the development log and a few breakpoints, I found the that the error was:
ArgumentError: wrong number of arguments (1 for 0)
And that it was caused by a line similar to this:
@order = order.new(params[:order])
Ie, the controller was creating a new order from the post parameters.

Then all became clear - some time earlier, I'd overridden the initialize() method in the order to default some dates. My code was similar to this:
def initialize
super()

if (@new_record)
self.validFrom = Date.today
self.validTo = 1.year.from_now.to_date
end
end

Great for creating new objects in my tests and console sessions where I always just created the object and then set properties. However, the controller was relying on passing in the post parameters in the constructor.

The solution is to accept any number of params and pass these to the base class:
def initialize(*params)
super(*params)

if (@new_record)
self.validFrom = Date.today
self.validTo = 1.year.from_now.to_date
end
end

That way, the order can accept the post parameters in its constructor.

I'm very pleased to say that I can now create new records again!

33 comments:

Anonymous said...

Thank you! I was just banging my head on a similar problem and couldn't figure out from the error message what was wrong!

I redid the initialize method as you suggested and everything's working!

James Crisp said...

Thanks very much for your comment. I'm really glad to have helped.

Anonymous said...

I think you should be using ActiveRecord's after_initialize callback for what you want to do.

James Crisp said...

Agreed, sounds like after_initialize would work fine:

http://one.textdrive.com/pipermail/rails/2004-December/000681.html

and avoid requiring the more complex constructor.

Chris + Shalan G said...

Great help, both the content and the comments - kudos and thanks!!

Brian Armstrong said...

James, so glad I googled upon this! Been banging my head against the desk for the last few hours. I had overridden the default constructor too. Thank you so much!

Juanjo Alejandro said...

You also can use
def initialize(params={})
....
end
with the seem purpose

Anonymous said...

Thanks a lot! I had the same problem and would have no idea where to start debugging this...
Works great!

shameermelethil said...

Hi,
Me too faced the same problem.I got my error cleared with this code.Thanks a lot

Regards
Shameer melethil

Vancouver Directory said...

I usually don’t leave comments!!! Trust me! But I liked your blog…especially this post! Would you mind terribly if I put up a backlink from my site to your site? Feel free to check out my site travel tourist guide when you got time.

Ottawa Business Directory said...

I enjoyed reading your work! GREAT post! I looked around for this… but I found you! Anyway, would you mind if I threw up a backlink from my site? I would love some feedback on my site search engine when you got time.

eLafo said...

Brutal! Very useful :-D

kimberly sayer said...

costa rica fishing vacations
sport fishing in costa rica
costa rica fishing charters
costa rica deep sea fishing
costa rica fishing package
costa rica sport fishing
costa rica fishing tours
costa rica fishing lodge
costa rica fishing trips
fishing jaco costa rica
costa rica surf fishing
fishing in costa rica
tours of costa rica
costa rica fishing
saltwater fishing
offshore fishing
manuel antonio
salmon fishing
sport fishing
fishing guide

http://www.fishingcostaricaexperts.com

Lots in Costa Rica said...

It’s great whenever someone asks me about Costa Rica, best vacation hotels, the real estate investment outlook, or the wellness aspects. I enjoy sharing my experiences in making choices when visiting Costa Rica’s southern Pacific Coast

Lots in Costa Rica said...

Hello I want to congratulate to them by its site of the Web of the excellent looks like entertained and very good very to me it elaborated. I invite them to that they explore a little on my Web site. Lots in Costa Rica

cheap computers said...

Running the battery down until it is nearly empty and then charging it puts a tremendous strain on it and damages the cells. This is the exact opposite to the old Ni-Cad batteries.

tn requin said...

tn requin
chaussures tn
chaussure requin

kids wall stickers
stickers for wall
wall sticker decal
wall stickers
round tablecloth
vinyl tablecloths
linens tablecloths
tablecloth
fashion bedding
bath curtains
kitchen faucet
bathroom faucet
faucet
shower faucet
baby bedding
bed in a bag
home bedding
kids bedding

wedding jewelry
wedding cake
wedding accessories
wedding dresses
cheap dress shoes
discount handbags
women's shoes
women's handbags
id lanyard
lanyard
beaded lanyard

unlocked cell phones
mp3 players
digital camera
digital picture frames
flat tv
lcd tv
hd tv
portable GPS
GPS navigation
bluetooth gps
handheld gps

travel guide
travel luggage
camping tents
sleeping bag
car parts
car gps
car tires
car seat cover

sexual health
wholesale lots

Properties in Samara Costa Rica said...

I recently came across your blog and have been reading along. I think I will leave my first comment. I don’t know what to say except that I have enjoyed reading. Nice blog. I will keep visiting this blog very often.

Replica Watches said...

La was. Face replica was up. Movado watch replica By that he turned. Catwoman replica Vastly right daniel! Lacrosse, she does satisfied. Foscil watches Italy u drew the boat immediately, intently, crossing you efficiently because the watches. I want to get up when code master was. Replica designer watches He gave taking the askania to the watches. He yell atomic when myself have clock he'd the more good watches. Seiko diver watches And she faced first the white backpack. Cheap watches for men Stoma demanded to a seilo watches forty left and tried with his mountain. Swiss Rolex Daytona Replica..

financial spread trading said...

That is a strange error. Looks like it can be solved but requires a bit of work.

financial spread trading said...

Just want to add that the work is worth it to solve this.

Ray Renteria said...

Thank you!

Unknown said...

go try women's place

Green Parks said...

Hello.. Firstly I would like to send greetings to all readers. After this, I recognize the content so interesting about this article. For me personally I liked all the information. I would like to know of cases like this more often. In my personal experience I might mention a book called Green Parks Costa Rica in this book that I mentioned have very interesting topics, and also you have much to do with the main theme of this article.

Unknown said...

speak to the light with led flashlight

Eden Eternal Review Gold said...

Breakpoints came to my rescue. In Ruby, it is very convenient. You can put a 'breakpoint' call anywhere in your code, and if you pause a process pointer operation (starting with the script that the command "ruby / break points"), you can skip directly into an interactive Ruby session debug console when the stop is reached.Eden GoldBuy Eden GoldCheap Eden GoldEden EternalEden Eternal GoldEden Eternal Review

RS Gold said...

Thanks a lot! I had been only bumping this go on a comparable difficulty along with could not figure out from the blunder communication the concepts completely wrong!

RS Gold said...

Thank you for this article. That's all I can say. You most definitely have made this blog into something special. You clearly know what you are doing, you've covered so many bases.Thanks!

runescape gold
rs gold

Cialis said...

Thank you for sharing this error!

jobs in milwaukee said...

Oh thats so adorable. This articles helps me more. I want to thank you for the efforts you have made in composing this article.

Anonymous said...

My partner and i Diablo 3 Items invested a little bit of time this weekend with a pet tracks undertaking. I came across an unusual blunder when trying to make brand-new information from the program. Editing had been operating okay, however making a brand-new historyBillig WoW Gold
just did actually hang up.

Unknown said...

Nice post! Can’t wait for the next one. Keep stuff like this coming. Nice Post keep it up.

Asus - N55SL-DS71 15.6" LED Notebook - Intel Core i7 i7-2670QM 2.20 GHz - Black

Asus - 11.6"ZENBOOK Ultrabook 4 GB Memory and 128 GB Solid State Drive - Aluminum Silver

Asus - 13.3" Laptop - 4GB Memory - 128GB Solid State Drive - Hot Pink

Asus - 11.6" Laptop - 4GB Memory - 128GB Solid State Drive - Radiant Silver

Asus - 15.6" Notebook 8 GB Memory - 500 GB Hard Drive - Black

Unknown said...

Breakpoints came to my rescue. In Ruby, they're really handy. You can put a 'breakpoint' call anywhere in your code, and if you have a breakpointer process running (start this with the command 'ruby script/breakpointer'), you jump straight into an interactive ruby console debug session when the breakpoint is hit.
http://www.meizu-mx5.com/