我需要根据注释的数量显示不同的文本,并将逻辑放在控制器中。但是在控制器中有一个很长的方法似乎不是很干,我应该把它放在哪里呢?
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>
我已经考虑过把逻辑放在一个部分,但这似乎不是很有效,因为我想渲染的文字只是一个句子。
答案 0 :(得分:2)
您可以将翻译方法添加到视图助手中。
def strong(comment_count)
case ...
end
然后您的视图将如下所示:
<%= strong(@comment_count) %>
你的控制器看起来像:
@comment_count = @user.comments.count
这很好,因为控制器没有任何显示逻辑,视图也很短。
答案 1 :(得分:0)
将视图代码移动到partial 例如_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) } %>