Rails 替代在视图中包含活动记录调用
我有一个看起来像这样的部分表单:
<%= form_for(@pool) do |f| %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :tournament %><br />
<%= f.collection_select :tournament_id, Tournament.active, :id, :name, :prompt => true %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
这看起来像代码味道,因为视图不应该负责了解如何获取
在 ASP.NET MVC 中,我只需将该字段拉出到部分视图中,并通过调用 RenderAction 来显示它,这将评估常见的控制器操作。然而,在 Rails 中 render :action => '/view' 似乎只允许渲染完整的视图。我对 Rails 还很陌生,所以我不确定最佳实践是什么。
I have a form partial that looks like this:
<%= form_for(@pool) do |f| %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :tournament %><br />
<%= f.collection_select :tournament_id, Tournament.active, :id, :name, :prompt => true %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
This seems like a code smell because the view shouldn't be responsible for knowing how to get the data for the <select>
tag. The alternative to have the controller assign an instance variable is problematic because I have to replicate that code in several actions depending on whether or not this form is rendered.
In ASP.NET MVC I'd just pull that field out into a partial view and display it with a call to RenderAction
Which would evaluate a common controller action. However, in Rails render :action => '/view'
seems to only allow full blown views to be rendered. I'm pretty new to Rails so I'm not sure about what the best practices are.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以按照 coder_tim 建议的方式执行辅助方法,但在我看来,这仍然将数据访问保留在视图中。
控制器是执行此操作的正确位置,如果您担心重复,请设置一个 before_filter ,仅作用于需要此集合的操作:
例如。
希望这有帮助。
You can do a helper method as coder_tim suggests, but in my opinion that still leaves data access in the view.
The controller is the proper place for this and if you're worried about duplication, set up a before_filter that only acts on the actions that need this collection:
for example.
Hope this helps.
我喜欢那段代码的味道:) 简单而不是极端。更少的文件 = 更少的方法 = 更干净的代码。
但是,有时在应用程序中使用下拉列表的次数过多,并且它比仅调用范围要复杂一些。在这种情况下,我会编写一个助手。
I like the smell of that code :) Simplicity over extremism. Less files = less methods to worry = cleaner code.
However, there are times when a dropdown is used too many times in your application, and it's a little more complicated than just calling a scope. In that cases, I write a helper.