在Rails 5中,当我根据其中一个字段搜索模型时,为什么会获取未定义的find_by方法?

问题描述:

II'm使用Rails 5.我想根据user_id字段搜索模型。我的表看起来像这样在Rails 5中,当我根据其中一个字段搜索模型时,为什么会获取未定义的find_by方法?

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 

但是当我试图查找一个模型,像这样

@user_notification = UserNotification.find_by_user(current_user) 

我得到的错误

undefined method `find_by_user' for UserNotification:Class 

什么是简单(Rails)的方式来看待我的领域?

find_by_user不是在rails中内置的方法,你必须在你的模型中定义它。

你应该用什么来查找记录的ID是Find。如果它存在,它将返回一个匹配输入ID的记录。

例:

@user_notification = UserNotifaction.find(1) 

并通过特定的领域找到,如自定义ID,使用find_by

@user_notification = UserNotifaction.find_by(custom_id: 1)