Rails:渲染模型?
我可以想到一百万种非自动的方法来在 Rails 中渲染模型,但我想知道是否有一些内置的方法可以做到这一点。 我希望能够
<%=@thing -%>
通过部分显然做到这一点,你可以做到这一点(我的意思是,调用 render :partial),但我想知道是否有一些标准方法来将视图与模型关联。
[提前感谢 weppos,修复了这个问题的标签:)]
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 :)]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不是来自海边吧? :) (我问是因为这正是那里的工作方式,每个模型/可渲染对象都知道如何渲染自身,这就是您布置页面的方式。)
关于您的实际问题,标准方法是通过渲染您将 @thing 提供给的部分。 (即,您对部分内容的看法是正确的,这就是视图通常与模型关联的方式。)
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.)
您可以重写模型中的
to_s
方法来返回所需的表示,尽管这不一定是可取的,因为这样您的模型就会包含正确属于您的视图的表示关注点。此外,to_s实际上是为了返回模型的简短字符串表示形式,可用于调试目的等。
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.如果您将模型直接传递给 render ,它将尝试渲染部分模型为了它。
那是一样的。
如果您传递模型数组...
它将为每个模型渲染
_thing
部分,就像您这样做一样。注意:这需要 Rails 2.3。 如果您有早期版本的 Rails,则需要使用 :partial 选项来执行相同的操作。
If you pass a model directly to render it will attempt to render a partial for it.
That is the same as.
If you pass an array of models...
It will render the
_thing
partial for each as if you did this.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.