should bookmark.id return nil
hey guys so i'm having issues adding a Like/Dislike function to my bookmarks on my page.
basically i have a snippet of code given to me that lives in my User model:
def liked(bookmark) likes.where(bookmark_id: bookmark.id).first end
however when i am running the server and clicking on the topic to show the associated bookmarks, i keep getting the
undefined method `id' for nil:NilClass
my question is... firstly what is going wrong here? and secondly, whats the difference between bookmark_id and bookmark.id?
im pretty sure id doesn't exist for bookmark... and if not... how would i add it? ive tried via migration, unfortunately nothing great came from that
use this code:
def liked(bookmark) likes.where(bookmark_id: bookmark.id).first if bookmark.present? end
You are getting id for nil:NilClass error due to object is not present.i.e bookmark object is nil.
bookmark_id is the field name for the bookmark class.And bookmark.id returns the id of the bookmark object, only if the object is present.
bookmark.id raises an exception. Ensure bookmark instance is passed to the liked method and is not nil
You need to ensure that your bookmark argument is not nil.
You could try the following code
def liked(bookmark) likes.where(bookmark_id: bookmark.try(:id)).first end
or an even better version
def liked(bookmark) likes.find_by(bookmark_id: bookmark.try(:id)) end
Above code will return a nil object or first like
To answer your second question, bookmark_id is an column name here for your Like model whereas bookmark.id is a method call on bookmark object.
You can try the following.
def liked(bookmark) likes.where(bookmark_id: bookmark.id).try(:first) unless bookmark.blank? end