ruby-on-railshelpermethods

Helper Method detect post - comment from user


I'm trying to create a helper method that will display {user.name} has no submitted posts." on the profile show view of user if they haven't yet submitted any posts and display the number posts they have . currently on my show view i have <%= render @user.posts %> which displays nothing when there are 0 posts submitted.

the partial for post is :

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

ive tried :

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

on my user show view :

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

which im more than sure is wrong but i have no idea how to implement this method .


Solution

  • Where you are using render @user.posts you can just add a simple conditional:

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

    There wouldn't be much point creating a helper for this unless you need to use it in multiple places.