In Rails 5, why do I get undefined find_by method when I search for a model based on one of its fields?

446 views Asked by At

II'm using Rails 5. I want to search for a model based on a user_id field. My table looks like this

cindex=# \d user_notifications;
                               Table "public.user_notifications"
       Column       |  Type   |                            Modifiers
--------------------+---------+-----------------------------------------------------------------
 id                 | integer | not null default nextval('user_notifications_id_seq'::regclass)
 user_id            | integer |
 crypto_currency_id | integer |
 price              | integer | not null
 buy  

          | boolean | not null

but when I attempt to look up a model like so

 @user_notification = UserNotification.find_by_user(current_user)

I get the error

undefined method `find_by_user' for UserNotification:Class

What's the simple (Rails) way to look up my field?

1

There are 1 answers

0
at0misk On BEST ANSWER

find_by_user is not a built in method in rails, you would have to define it in your model.

What you should use to find a record by it's id is simply Find. It will return one record matching the inputed id if it exists.

Ex:

@user_notification = UserNotifaction.find(1)

And to find by a specific field, such as a custom id, use find_by

@user_notification = UserNotifaction.find_by(custom_id: 1)