2017-03-06 94 views
0

我想要實現的是一個標籤,顯示頁面上有多少評論。目前,代碼用於顯示我需要的內容,但我認爲這不是正確的方式,可以使用一些重構。我應該如何重構這個條件助手?

此外,我是否應該將h1標記移出到視圖中,或者是content_tag可接受?

我需要的基本上是如果沒有評論和複數的標籤,如果有評論,「成爲第一個評論」。

感謝您的幫助。

def number_of_comments 
    @review.comments.count 
    end 

    def render_comments_count 
     if number_of_comments == 0 
     content_tag(:h1, "Be the first to comment") 
     elsif number_of_comments == 1 
     content_tag(:h1, "1 comment") 
     else 
     content_tag(:h1, number_of_comments) + content_tag(:h1, "comments") 
     end 
    end 
    end 

回答

0

您可以使用複數化並提取H1的觀點:

def number_of_comments 
    @review.comments.count 
end 

def render_comments_count 
    if number_of_comments.zero? 
    'Be the first to comment' 
    else 
    "#{number_of_comments} #{'comment'.pluralize(number_of_comments)}" 
    end 
end 

然後,在視圖中:

<h1><%= render_comments_count %></h1> 
+0

大,爲此感謝! – Joshua