Wednesday, April 16, 2008

respond_to + render :partial

RoR has a very quick way to turn your web application into a web service that supports API hooks into your application. It does this using the respond_to method. It's as simple as doing something like:

respond_to do |format|
format.html # automatically calls the corresponding view
format.js #automatically calls the corresponding rjs
format.xml { render :xml => @user.to_xml # or other XML stuff }
end

It's that simple!

Well, there's one odd thing that got me for a little bit. I'm not sure if it's a bug, but when I tried to render a partial in the format.js block, I got an error that it could not find the corresponding template:

respond_to do |format|
format.js { render :partial => 'my_partial' }
end

I found that very odd, but not fixable... I tried adding '.html.erb' to the end of my_partial:

format.js { render :partial => 'my_partial.html.erb' }

And magic! It worked! I'm almost sure this isn't the way RoR is suppose to handle this, but in the meantime, it works! Small hack, but I'm happy :D If any one else runs into this problem, drop a comment, or even better, if you know why or how to solve this, let me know!


W

No comments: