Rails: Rendering Models?

笑着哭i 提交于 2019-12-07 10:13:40

问题


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:


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 %>



回答2:


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.




回答3:


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.)



来源:https://stackoverflow.com/questions/1260682/rails-rendering-models

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!