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 :)]
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 %>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With