II'm using Rails 5. I want to search for a model based on a user_id field. My table looks like this
我正在使用Rails 5.我想基于user_id字段搜索模型。我的桌子看起来像这样
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?
查看我的领域的简单(Rails)方法是什么?
2 个解决方案
#1
1
find_by_user
is not a built in method in rails, you would have to define it in your model.
find_by_user不是rails中的内置方法,您必须在模型中定义它。
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.
您应该使用它来查找记录的id是简单的查找。它将返回一个匹配输入id的记录(如果存在)。
Ex:
例如:
@user_notification = UserNotifaction.find(1)
And to find by a specific field, such as a custom id, use find_by
要通过特定字段(例如自定义ID)查找,请使用find_by
@user_notification = UserNotifaction.find_by(custom_id: 1)
#2
0
@user_notification = UserNotification.find_by_user_id(current_user.id)
#1
1
find_by_user
is not a built in method in rails, you would have to define it in your model.
find_by_user不是rails中的内置方法,您必须在模型中定义它。
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.
您应该使用它来查找记录的id是简单的查找。它将返回一个匹配输入id的记录(如果存在)。
Ex:
例如:
@user_notification = UserNotifaction.find(1)
And to find by a specific field, such as a custom id, use find_by
要通过特定字段(例如自定义ID)查找,请使用find_by
@user_notification = UserNotifaction.find_by(custom_id: 1)
#2
0
@user_notification = UserNotification.find_by_user_id(current_user.id)