辅助方法检测 post - 来自用户的评论

Helper Method detect post - comment from user

我正在尝试创建一个辅助方法,如果用户尚未提交任何 post,它将在用户的个人资料显示视图中显示 {user.name} has no submitted posts." 并显示数字 [=26] =]s 他们有。目前在我的显示视图中,我有 <%= render @user.posts %>,当提交 0 post 时,它什么也不显示。

post 的部分是:

<div class="media">
  <%= render partial: 'votes/voter', locals: { post: post } %>
  <div class="media-body">
    <h4 class="media-heading">
      <%= link_to post.title, topic_post_path(post.topic, post) %>
      <%= render partial: "labels/list", locals: { labels: post.labels } %>
    </h4>
    <small>
      submitted <%= time_ago_in_words(post.created_at) %> ago by <%= post.user.name %> <br>
      <%= post.comments.count %> Comments
    </small>
  </div>
</div>

我试过了:

  def no_post_submitted?(user)
      user.post.count(0)
      "{user.name} has not submitted any posts yet."
  end

在我的用户显示视图中:

<%= if no_post_submitted?(@user) %>
<%= render @user.posts %>

我肯定是错的,但我不知道如何实现这个方法。

在您使用 render @user.posts 的地方,您可以添加一个简单的条件:

<% if @user.posts.empty? %>
  <p><%= @user.name %> has no submitted posts</p>
<% else %>
  <%= render @user.posts %>
<% end %>

除非您需要在多个地方使用它,否则为此创建一个帮助程序没有多大意义。

在Ruby方法中自动return最后一个值所以这个方法:

def no_post_submitted?(user)
  user.post.count(0)
  "{user.name} has not submitted any posts yet."
end

总是 return 字符串 - 如果您在条件中使用字符串文字,它将被评估为 true 并带有警告 warning: string literal in condition。这也不是您使用 count 的方式 - 传递 0 将导致它查询第 0 列或只是错误。

所以要修正你会做的方法:

def no_post_submitted?(user)
  user.posts.empty?
end

然而,这个条件非常简单,它并不真正需要一个辅助方法。相反,您只需写:

<%= if user.post.any? %>
  <%= render @user.posts %>
<% else %>
  <%= "{user.name} has not submitted any posts yet." %>
<% end %>

渲染集合 returns 如果集合为空则为 nil,这样您就可以使用 ||运算符:

<%= render @user.posts || "{@user.name} has not submitted any posts yet." %>

或者如果有更多代码渲染另一个部分:

<%= render @user.posts || render 'no_posts' %>

您的解决方案存在一些问题。请记住,rails 更多的是约定优于配置。

您的方法 no_post_submitted? 实际上应该 return true/false 因为它是一个以 ? 结尾的方法。为清楚起见,它还应命名为 no_posts_submitted?。它应该看起来像这样:

  def no_post_submitted?(user)
    user.posts.count > 0
  end

然后,应该有另一个辅助方法可以打印您需要的消息,例如:

def no_posts_message(user)     
  "{user.name} has not submitted any posts yet."
end

最终你们都可以像这样插入它:

<% if no_posts_submitted?(user) %>
 <%= no_posts_message(user) %>
<% else>
 <%= render @user.posts %>
<% end %>

根据 docs:

In the event that the collection is empty, render will return nil, so it should be fairly simple to provide alternative content.

<h1>Products</h1>
<%= render(@products) || "There are no products available." %>

--

所以...

  <%= render(@user.posts) || "#{@user.name} has not submitted any posts yet." %>