views:

807

answers:

3

Im curious about what the best way to load a rails partial with jquery. So far I have tried a solution not working:

$('#imagecontent').load('/newsletters/_image_gallery.html.erb', function() {
alert('Load was performed.');
});

Is the best solution to build a seperate action and/or controller for this and set up a route? Im asking because making the first solution work seems more easy, perhaps not so restful.

Thanks.

+3  A: 

You should not be able to access Template files (.erb) from HTTP requests, this is very bad practice. I suggest you put them outside your web servers path and access them only through your application.

I'm not sure about Rails, but I suppose you need to create a separate controller (or whatever) to do this.

EDIT this is because .erb files are Embedded Ruby files, and if you try to request them you will get all unwanted data, like <%= page_title %>, that you don't want to show the users. Therefore you need to pass these .erb files through your Rails application so that they are properly interpreted into HTML.

Luca Matteis
ok - thanks for the insight. I will structure it accordingly.
+1  A: 

The reason that code doesn't work is that rails doesn't expose view files outside. To achieve the thing you want, you'll need an action which would render this partial:

def image_gallery
  render :partial => "image_gallery"
end

Also there is a plugin called jRails which replaces standard ajax helpers (which use prototype) with equivalent jquery-oriented ones. In your case you would use something like

<%= remote_function(:update => "imagecontent", :url => "/newsletters/image_gallery") %>

And even more, in Rails 3 you won't need it. See this link.

neutrino
thanks - Im looking forward to see all new stuff in Rails 3.
A: 

Here's what you want:

http://www.slideshare.net/JamesEdwardGrayII/ajax-with-jquery-in-rails

volante