Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Rendering Models?

I can think of a million not-so-automatic ways to render a model in Rails, but I'm wondering if there's some built-in way to do it. I'd like to be able to this

<%=@thing -%>

obviously with partials you can do it (I mean, calling render :partial), but I'm wondering if there's some standard way to associate views with models.

[Thanks in advance, weppos, for fixing the tags on this question :)]

like image 741
Dan Rosenstark Avatar asked Dec 08 '22 06:12

Dan Rosenstark


2 Answers

If you pass a model directly to render it will attempt to render a partial for it.

<%= render @thing %>

That is the same as.

<%= render :partial => 'things/thing', :object => @thing %>

If you pass an array of models...

<%= render @things %>

It will render the _thing partial for each as if you did this.

<%= render :partial => 'things/thing', :collection => @things %>

Note: this requires Rails 2.3. If you have earlier versions of Rails you'll need to use the :partial option to do the same thing.

<%= render :partial => @thing %>
like image 98
ryanb Avatar answered Dec 19 '22 12:12

ryanb


You could override the to_s method in your model to return the representation that you want, although this isn't necessarily desirable because then your model contains presentation concerns that correctly belong in your view.

Besides, to_s is really meant to return a short, string representation of your model useful for debugging purposes etc.

like image 34
John Topley Avatar answered Dec 19 '22 13:12

John Topley