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
<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 %>- Jenny Crawshaw<% if like = current_user.liked(bookmark) %>- Jenny Crawshaw=> #<Bookmark id: 1, url: "http://localhost:3000/topics/11/bookmarks/new", topi c_id: 11, created_at: "2015-02-17 19:28:17", updated_at: "2015-02-17 19:28:17", user_id: 1, bookmark_id: nil> 2.0.0-p481 :003 >So there is a bookmark id at the beginning, but it is still showing nil for the bookmark_id? - Jenny Crawshawlikedfunction inusers.rbtoLike.where(bookmark: bookmark.id).first- jpriebe