Reputation: 93
I am having trouble solving this problem. I keep getting the same error: ActionView::Template::Error (undefined method `id' for nil:NilClass):
Here is my likes controller:
class LikesController < ApplicationController
def new
@bookmark = Bookmark.find(params[:bookmark_id])
@like = Like.new
end
def create
@bookmark = Bookmark.find(params[:bookmark_id])
# @like = Like.new
# @like.user = current_user
# @like.bookmark = @bookmark
@like = current_user.likes.build(bookmark: @bookmark)
if @like.save
flash[:notice] = "Bookmark was Liked!"
redirect_to @bookmark
else
flash[:error] = "Unable to Like Bookmark"
redirect_to @bookmark
end
end
def destroy
#@bookmark = Bookmark.find(params[:bookmark_id])
@like = @bookmark.likes.find(params[:id])
if @like.destroy
flash[:notice] = "Bookmark was Un-liked."
redirect_to @bookmark
else
flash[:error] = "Error Un-liking bookmark."
redirect_to @bookmark
end
end
end
My User model:
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :confirmable
has_many :topics
has_many :bookmarks
has_many :likes, dependent: :destroy
def liked(bookmark)
likes.where(bookmark: bookmark.id).first
end
end
My likes partial:
<div>
<% if like = current_user.liked(bookmark) %>
<%= link_to [@topic, bookmark, like], class: 'btn btn-danger', method: :delete do %>
<i class="glyphicon glyphicon-star-empty"> </i> Unlike
<% end %>
<% else %>
<%= link_to [@topic, bookmark, Like.new], class: 'btn btn-primary', method: :post do %>
<i class="glyphicon glyphicon-star"> </i> Like
<% end %>
<% end %>
</div>
Let me know if I need to show anything else, I appreciate any help
Upvotes: 1
Views: 1660
Reputation: 7405
From where you are calling the partial try this :
<% @bookmarks.each do |bookmark| %>
<%= render partial: 'likes/like', locals: {bookmark: bookmark} %>
<% end %>
Upvotes: 2
Reputation: 4255
In your likes partial, you have:
<% if like = current_user.liked(bookmark) %>
That =
should be a ==
. With a single equals, you're checking whether the like variable is assigned a truthy value, based on current_user.liked(bookmark)
. You want a double equals to test equality.
UPDATE If you really mean to both assign and compare, split it into two lines so it looks like it's intentional. It's a microexample of the "Command / Query Separation Principle."
<% like = current_user.liked(bookmark) %>
<% if like %>
(Sorry this probably doesn't relate directly to your question, but it was very distracting to see.)
Upvotes: 0