should 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)

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

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: if bookmark.present?
  1. You are getting id for nil:NilClass error due to object is not present.i.e bookmark object is nil.

  2. bookmark_id is the field name for the bookmark class.And returns the id of the bookmark object, only if the object is present. 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

or an even better version

def liked(bookmark)
  likes.find_by(bookmark_id: bookmark.try(:id))

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 is a method call on bookmark object.

You can try the following.

def liked(bookmark)
  likes.where(bookmark_id: unless bookmark.blank?

Need Your Help

CodeIgniter Validation in Library does not accept callback

php validation codeigniter callback

my problem is the following: I am writing a login library.

How paint() in a CLONE JPanel?

java swing clone jpanel paint

Anybody know how can I repaint in a clone JPanel. Im using CLONE, so I can REPAINT() one, and the other will do the same automatically.