0

我需要根据评论的数量显示不同的文本,并且我已经将逻辑放在了控制器中。但是在控制器中有一个长方法似乎不是很干,我应该把它放在哪里呢?

example_controller.rb:

def index
  .
  count_dependent_message
  .
end

def count_dependent_message
  case @user.comment.count
        when 0
          @strong = "example Strong 0"
          @paragraph = "example paragraph 0"
        when 1
          @strong = "Jon Smith is called Smith"
          @paragraph = "example paragraph 1"
        when 2...10
          @strong = "Once upon a time...Steve Jobs... "
          @paragraph = "example paragraph 2"
        when 11...40
          @strong = "Wow you have many counts"
          @paragraph = "example paragraph 3"

        else
          @strong = "exciting"
          @paragraph = "example paragraph 4"  
  end
end

看法:

<h3>
 <strong>
  <%= @strong %>
 </strong>
</h3>
<p>
<%= @paragraph %>
</p>

我考虑过将逻辑放在部分中,但这似乎不是很有效,因为我要渲染的文本只是一个句子。

4

2 回答 2

2

您可以将翻译方法添加到视图助手。

def strong(comment_count)
   case ...
end

然后您的视图将如下所示:

<%= strong(@comment_count) %>

您的控制器将如下所示:

@comment_count = @user.comments.count

这很好,因为控制器不会有任何显示逻辑并且视图也会很短。

于 2012-12-15T02:31:04.580 回答
0

将视图代码移动到部分,例如 _heading.html.erb

<h3>
 <strong><%= texts[:heading] %></strong>
</h3>
<p><%= texts[:text] %></p>

而 count_dependent_message 方法应该是

    def count_dependent_message(count = nil)
      case count
      when 0
        { :heading => "example Strong 0", :text => "example paragraph 0" }
      when 1
        { :heading => "Jon Smith is called Smith", :text => "example paragraph 1" }
      when 2...10
        { :heading => "Once upon a time...Steve Jobs... ", :text => "example paragraph 2" }
      when 11...40
        { :heading => "Wow you have many counts", :text => "example paragraph 3" }
      else
        { :heading => "exciting", :text => "example paragraph 4" }
      end
    end

因此你可以打电话

<%= render 'heading', :locals => { :texts => count_dependent_message(@user.comment.count) } %>
于 2012-12-15T00:13:13.393 回答