views:

107

answers:

3

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 :)]

+1  A: 

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.

John Topley
Exactly. I've been adding a .to_html on the model, but that's the TOTALLY wrong place for view code. Which you mention. Anyway, thank you.
Yar
+1  A: 

You’re not coming from Seaside are you? :) (I ask because this is exactly how things work there, where each model/renderable object knows how to render itself, and that’s how you lay the page out.)

In regards to your actual question, the standard way to do it is by rendering a partial that you feed your @thing to. (i.e. you’re right on the money about the partials, and that’s the way views are typically associated with models.)

EdwardOG
Nope, Seaside for me is just a place on the Jersey short. http://en.wikipedia.org/wiki/Seaside_Heights,_New_Jersey
Yar
This way of thinking is very OO, though, and that's typical of smalltalk.
Yar
+4  A: 

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 %>
ryanb
Wow. This was what I was looking for. Good stuff, thank you.
Yar