Question

I'm trying to create helpers to clean up my views. I create one to only allow the owner of a post to edit or delete it.

 module ConversationsHelper

  def editing_for_current_user (convo)
    if current_user == convo.user
      link_to 'Edit', edit_conversation_path(convo), class: 'btn btn-primary btn-sm'
      link_to 'Delete', convo, method: :delete, data: { confirm: 'Are you sure?' }, class: 'btn btn-primary btn-sm'
    end
  end
end

This is my view:

<div class="row">
<% @conversations.each do |conversation| %>
    <div class="col-sm-6 col-md-4">
      <div class="thumbnail">
            <h3><%= link_to conversation.title, conversation %></h2>
            <p>Comments: <span class='badge'><%= conversation.comments.count %></span></p>
            <p><%= conversation.description %></p>
            <p><b>Submitted by:</b> <%= link_to conversation.user.username, user_path(conversation.user.id) %></p>
            <h3> Recent comments: </h3>
            <hr>
            <% conversation.comments.sort_by{|t| - t.created_at.to_i}.take(3).each do |c| %>
                <div class='media'>
                    <%= image_tag c.user.profile_pic.url(:thumb), class: 'media-object pull-left img-polaroid' %>
                  <div class='media-body'>
                    <h4 class='media-heading'><%= link_to c.user.username, user_path(c.user.id) %><small> @ <%=c.created_at.strftime("%m/%d/%Y at %I:%M%p") %></small></h4>
                    <%= simple_format(c.message) %>
                  </div>
                </div>
                <hr>
              <% end %>
            <%= editing_for_current_user(conversation) %>
      </div>
    </div>
<% end %>


However, only the 'Delete' link shows up. Is there a way to display both the link_to's without creating another method?

Thanks in advance.

Was it helpful?

Solution

This kind of thing is something better handled in a partial. What you want is another file in your view directory like this:

_edit_links.html.erb

<%= link_to 'Edit', edit_conversation_path(conversation), class: 'btn btn-primary btn-sm '%>
<%= link_to 'Delete', conversation, method: :delete, data: { confirm: 'Are you sure?' }, class: 'btn btn-primary btn-sm' %>

Then in your conversation show (or whichever file you have there):

<%= render "edit_links" if current_user == conversation.user %>

Partials should be used when you want to split up the things on your show pages to make them more readable and/or maintainable. Helpers are useful when you have more complex methods that you call a lot. For instance, if you were checking if an object belongs to the person signed in multiple times, you might write a helper method like this:

def belongs_to_current_user rec
  current_user == rec.user
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top