Masen
Masen

Reputation: 53

Can you restrict a link_to element in Rails to only be visible if you're logged in as an admin?

So I'm trying to make a new portfolio site in Rails and I'm trying to work out the admin component of it. Specifically, there's a blog feature and I want to be the only one who can view new/edit/delete/etc. features on the blog itself. If someone isn't logged in as an admin, I want them to see the same page without being able to view the links to these options.

Right now, the view looks like this:

<div class="content has-text-centered">
  <h1 class="title">Blog</h1>
</div>

<section class="section">
  <tbody>
    <% @posts.each do |post| %>
      <tr>
        <td><%= link_to 'Show', post %></td>
        <td><%= link_to 'Edit', edit_post_path(post) %></td>
      </tr>
    <% end %>
   </tbody>
</table>
<br>
</section>

<%= link_to 'New Post', new_post_path %>

...and I'm basically trying to get it to the point where only the first three lines are visible on the page itself unless the user is logged in as an admin.

Any advice on how to handle this? I'm using Ruby 2.4.1, Rails 5.2.0, and Devise 4.4.3. Thanks!

Upvotes: 0

Views: 115

Answers (1)

Billy Kimble
Billy Kimble

Reputation: 820

Use the user_signed_in? method, and only show that block if it returns true:

<div class="content has-text-centered">
  <h1 class="title">Blog</h1>
</div>

<% if user_signed_in? %>
  <section class="section">
    <tbody>
      <% @posts.each do |post| %>
        <tr>
          <td><%= link_to 'Show', post %></td>
          <td><%= link_to 'Edit', edit_post_path(post) %></td>
        </tr>
      <% end %>
     </tbody>
  </table>
  <br>
  </section>
<% end %>

This is assuming your devise user model is 'User'. If its 'Admin' then it would be

<% if admin_signed_in? %>

See https://github.com/plataformatec/devise/wiki/How-To:-Add-sign_in,-sign_out,-and-sign_up-links-to-your-layout-template for more information.

Upvotes: 3

Related Questions