Thomas
Thomas

Reputation: 723

Conditional link display in rails

I have a filter bar on my page. The bar should always be in place, however only when I'm on the detail page I want to show a link <- back to list inside of it. Otherwise the filter bar should be empty. What is the most elegant way of doing this in rails 3 or 3.1?

Thanks Thomas

Upvotes: 0

Views: 310

Answers (2)

mliebelt
mliebelt

Reputation: 15525

From your question and the comment, you have the following structure:

application.html.erb:
...
<section id="filter-bar"> 
  <section id="filter"></section> 
</section>

I see there two different options how to include your link conditionally:

  1. By doing an if-then in your file application.html.erb
  2. By including a yield with a symbol that denotes the context.

Here is the pseudo-code for that:

  1. solution

    application.html.erb:
    ...
    <section id="filter-bar"> 
      <section id="filter">
        <% if controller_name == 'user' && action_name == 'show' %>
          <%= link_to "Back", :index %>
        <% end %>
      </section> 
    </section>
    
  2. solution

    application.html.erb:
    ...
    <section id="filter-bar"> 
      <section id="filter">
        <%= yield(:filter) %>
      </section> 
    </section>
    
    view.html.erb:
    <%- content_for :filter do %>
      <%= link_to "Back", :index %>
    <% end %>
    ...
    
    index.html.erb:
    // No content_for section in the file, so it will be empty here.
    

The first solution is simpler, much more condensed, but all the information if something is included or not is in one file. If that is changed a lot, that may be a hotspot in your application. The second is more object-oriented, but perhaps more to change and think about. But both will working for you.

Upvotes: 0

Fernando Almeida
Fernando Almeida

Reputation: 3174

To return to previous page you can use link_to "Back", :back

To show or hide the link you can use the controller_name and action_name methods with a if/unless conditional.

Upvotes: 1

Related Questions