Wasabi Developer
Wasabi Developer

Reputation: 3553

Using a params condition to display a link_to when a user visits the show action on a specific controller

How does one setup a condition if 'post_controller/show' is viewed.

I would like an 'Edit' button to display on the header navigation if the user is viewing the post, without setting up a different layout and have it just rely on the existing _header.html.erb for navigation.

# Header navigation partial _header.html.erb
<%= link_to 'Edit post', edit_post_path(@post) %>

I know I can take a param and set clause something like:

<% if params[:id] %>
  <%= link_to 'Edit post', edit_post_path(@post) %>
<% end %>

The problem with the above is it will cause an exception undefined method 'edit_post' if you visit a different route that doesn't relate to the Post model.

If I can get away from many layouts and partials that would great but if the suggestion is that I should be using layouts and partials in this scenario then I will.

Many thanks all.

Upvotes: 0

Views: 108

Answers (1)

Anthony Alberto
Anthony Alberto

Reputation: 10395

# Header navigation partial _header.html.erb
<%= yield(:edit_link) %>

#In your post_controller/show view :
<% content_for :edit_link, link_to('Edit post', edit_post_path(@post)) %>

And that's about it. You can change the content of :edit_link wherever you want, for different models etc ...

Upvotes: 2

Related Questions