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

"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”

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

"comment_display", :collection => @all_crazy_comments %>

Where @all_crazy_comments is an array of comments.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s