如何使该案例陈述起作用?

cam

在我看来,我正在这样做:

<% case @post 
 when @post.has_children? %>
    <% @post.children.each do |child| %> 
            <li><%= link_to child.title, post_path(child)%></li>        
    <% end %>
<% when @post.has_siblings? %>
    <% @post.siblings.where.not(id: @post.id).each do |sibling| %>
            <li><%= link_to sibling.title, post_path(sibling)%></li>                    
    <% end %>
<% when [email protected]? %>
        <li><%= link_to @post.parent.title, post_path(@post.parent) %></li>
<% else %>
    </ul>
</p>
<p>
    There are no related posts.
</p>
<% end %>

基本上我想做的就是检查@post各种条件。如果它has_children?,如果它has_siblings?,等等。

如果上述任何一项是对还是错,我都不希望该语句退出。

视图加载后,它应自动检查所有这些语句。如果发现以上任何一项为真,则应在检查下方执行命令。

问题是当我这样做时,它始终默认为else即,案例陈述不起作用。

我知道我可以简单地执行一堆脱节的if语句,但是周围的HTML有点怪异。

有没有办法用CASE语句来做到这一点?

编辑1

if语句无法正常运行的原因是,如果我有3条if背对背的语句-没有一条彼此交互(这是正确循环所有条件的唯一方法),那就是else不会触发适当地。

例如,如果前两个条件为真,但第三个条件不是……它将打印出来"there are no related posts"……如果不是这样。情况是没有parent帖子。

基本上,我只想拥有一个通俗易懂的related文章,所以我只是简单地遍历所有各种选项并检查是否存在这些关系。如果他们这样做,我会把他们拉出来,如果他们不这样做,那么他们会继续前进。如果不存在,那么我不会打印“没有相关的帖子”。

皮特

视图已经看起来很复杂的事实表明,将逻辑从视图中重构出来并将其放入其所属的Post模型中可能是个好主意。理想情况下,视图应最终看起来像这样:

<%# posts/show.html.erb %>
<% if @post.has_related_posts? %>
   <%= render partial: 'children', collection:  @post.children, as: :child %> 
   <%= render partial: 'siblings', collection:  @post.other_siblings, as: :sibling %> 
   <%= render partial: 'parent', locals:  {parent: @post.parent}%> 
<% else %>
  <p>There are no related posts</p>
<% end %>

主题词:

<%# posts/_children.html.erb %>
<li><%= link_to child.title, post_path(child)%></li>


<%# posts/_sibling.html.erb %>
<li><%= link_to sibling.title, post_path(sibling)%></li>

<%# posts/_parent.html.erb %>
<% unless parent.nil? %>
  <li><%= link_to parent.title, post_path(parent) %></li>
<% end %>

然后Post模型可以组织逻辑:

class Post < ActiveRecord::Base
  def has_related_posts?
    !children.to_a.empty? || !other_siblings.to_a.empty? || !parent.nil?
  end

  def children
    self.children || [] # Rails does this automatically, but just for the example
  end

  def other_siblings
    self.siblings.where.not(id: self.id)
  end

  #...
end

我知道这并不能直接回答您的问题,但是恕我直言,我认为这是一个更好的解决方案。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章