Saturday, February 18, 2006

Rails Collections and Partials

I like convention, mostly because it simplifies what needs to be said, because it can be implied. But likewise, it makes it difficult for newcomers to know what these conventions are, because they're usually not written anywhere.

When rendering a partial, a parital has access to all instance variables generated by the controller method. So if you were rendering a method from show_comments, @my_crazy_comment would be available to the partial. But not only that, if the partial is called with

<%= render :partial => "comment_display", :object => @my_crazy_comment %>

The partial would have available to it, a variable called 'comment_display' that points to @my_crazy_comment.

So inside your partial file, "_comment_display.rhtml"

<%= comment_display.comment %>
<%= %>

The variable "comment_display" will have the comment in @my_crazy_comment. For a collection of partials, it's just as easy.

<%= render :partial => "comment_display", :collection => @all_crazy_comments %>

Where @all_crazy_comments is an array of comments.

No comments:

Post a Comment