简体   繁体   English

将这样的逻辑移到控制器或模型而不是视图?

[英]Move logic like this to the controller or model rather than the view?

I have this logic currently in my view 我目前有这种逻辑

<% tools_count = @job.tools.count - 1 %>
    <% count = 0 %>
    <% @job.tools.each do |u|%>
        <%= u.name %>
        <% if count != tools_count  %>
        <% count += 1 %>
        <%= "," %>
    <%end%>
<% end %>

Which just loops through some users relations and puts in a , unless it is the end of the list. 只是循环通过一些用户关系,并放入一个,除非它在列表的末尾。

My question: This kind of logic looks really messy and clogs up my views I know there must be a better way of doing this by moving it into the controller or maybe model, does anyone know the correct way to do this kind of logic? 我的问题:这种逻辑看起来真的很混乱,并且堵塞了我的观点,我知道必须通过将其移入控制器或模型中来找到一种更好的方法,有人知道正确的方法吗?

You can add a method like this to your Job model: 您可以将以下方法添加到Job模型中:

def tool_names
  tools.map(&:name).join(',')
end

And use it in your view like this: 并在您的视图中使用它,如下所示:

<%= @job.tool_names %>

There are couple of ways to avoid putting this kind of logic in the view layer: 有几种方法可以避免将这种逻辑放入视图层:

  1. Create an instance method in the model class (as spickermann suggested) 在模型类中创建实例方法(如spickermann建议)

This will work for simple logic and simple projects. 这将适用于简单的逻辑和简单的项目。 However, when you will want to use some helpers from ActionView::Helpers such as jobs_path or number_to_currency , a model is not a good place for it. 但是,当您想使用ActionView::Helpers一些ActionView::Helpers例如jobs_pathnumber_to_currency ,模型不是合适的选择。

  1. Create a helper method in helper modules eq. 在助手模块eq中创建一个助手方法。 JobHelpers

Generally you can put any helper methods related to view layer in helpers. 通常,您可以将与视图层相关的任何帮助程序方法放入帮助程序中。 For example to share common methods for building a view components. 例如,共享用于构建视图组件的通用方法。

  1. Use the decorator/presenter pattern and put there the view logic so model won't be polluted. 使用装饰器/演示器模式,并放置视图逻辑,这样就不会污染模型。 Here is some more explanation about the pattern and sample implementation using draper gem: http://johnotander.com/rails/2014/03/07/decorators-on-rails/ 这是有关使用draper gem的模式和示例实现的更多说明: http : //johnotander.com/rails/2014/03/07/decorators-on-rails/

您可以像这样一行

<%= @job.tools.map(&:name).join(',') %>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM