ruby-on-rails - 我怎样才能让这个案例陈述发挥作用?

标签 ruby-on-rails ruby-on-rails-4

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

<% 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 <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c4e584b4abb7b0eab4a5b6a1aab0eaaaada8" rel="noreferrer noopener nofollow">[email protected]</a>? %>
        <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?,等等

如果上述任一情况为真或为假,我不希望语​​句退出。

加载 View 后,它应该自动检查所有这些语句。如果发现上述任一情况为真,则应执行检查正下方的命令。

问题是当我这样做时,它总是默认为else。即 case 语句不起作用。

我知道我可以简单地执行一堆不连贯的 if 语句,但是围绕它的 HTML 会变得有点奇怪。

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

编辑 1

if 语句无法正常工作的原因是,如果我有 3 个背靠背的 if 语句 - 其中没有一个是相互交互的(这就是正确循环所有条件的唯一方法)是 else 无法正确触发。

例如如果前两个条件为真,但第三个条件不为真...它将打印出“没有相关帖子”...当情况并非如此时。情况是没有帖子。

基本上我只是想拥有一个包罗万象的相关帖子,所以我只是迭代所有不同的选项并检查这些关系是否存在。如果他们这样做了,我就把他们拉出来,如果他们不这样做,那么他们就会继续前进。如果不存在,那么我不会打印“没有相关帖子”。

最佳答案

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

<%# 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

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

关于ruby-on-rails - 我怎样才能让这个案例陈述发挥作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27164731/

相关文章:

ruby-on-rails - Rails 4 总是为列添加空值

ruby-on-rails - 将复选框和标签与 collection_check_box 对齐

ruby-on-rails - Rails Engine gem 使用来自 git 的另一个 Rails 引擎 gem

ruby-on-rails - 如何在 Rails 4 Controller 中为 "allow-from" "X-Frame-Options"多个域?

ruby-on-rails - 如何在 json 中不渲染任何内容?

ruby-on-rails - 单元测试运行三次

ruby-on-rails - Rails 基本 Base64 身份验证

ruby-on-rails - 如何将命名范围应用于轮胎搜索结果?

javascript - 未终止的正则表达式文字js错误

ruby-on-rails - 是否可以使 Ohm for Ruby 中的整个对象的内容过期?