I have an if statement that displays certain link based if a user voted or not for something. However, I'll get an error if the user is not logged in since current_user will be nil. I'm using devise for authentication.
undefined method `voted_as_when_voted_for' for nil:NilClass
<% if current_user.voted_as_when_voted_for @pin %>
<%= link_to dislike_pin_path(@pin), method: :put, class: "btn btn-default" do %>
<span class="glyphicon glyphicon-heart"></span> <%= @pin.get_upvotes.size %>
<% end %>
<% else %>
<%= link_to like_pin_path(@pin), method: :put, class: "btn btn-default" do %>
<span class="glyphicon glyphicon-heart"></span>
<%= @pin.get_upvotes.size %>
<% end %>
<% end %>
<%= link_to pins_path, class: "btn btn-default" do %>
<span class="glyphicon glyphicon-step-backward"></span>
Back
<% end %>
<% if user_signed_in? %>
<%= link_to "Edit", edit_pin_path, class: "btn btn-default" %>
<%= link_to "Delete", pin_path, method: :delete, data: { confirm: "Are you sure"}, class: "btn btn-default" %>
<% end %>
What can I add to that if statement to display one of the links even if the user is not logged in without repeating link_to code. Using DRY Rails methodology. (if a user is not logged in and clicks like/dislike link, it will ask him to log in since I have my routes set up like this:
before_action :authenticate_user!, except: [:index, :show]
Try this:
<% if current_user && current_user.voted_as_when_voted_for @pin %>
... code here
<% else %>
<%= link_to like_pin_path(@pin), method: :put, class: "btn btn-default" do %>
<span class="glyphicon glyphicon-heart"></span>
<%= @pin.get_upvotes.size %>
<% end %>
<% end %>
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments