【发布时间】:2020-08-23 02:11:13
【问题描述】:
我试图了解我在这里做错了什么 - 如果有人能指出我正确的方向,那就太好了!
我的应用中有以下关联:
class Notification < ApplicationRecord
belongs_to :notificationable, polymorphic: true
end
class AccessPermission < ApplicationRecord
belongs_to :project
has_many :notifications, as: :notificationable, dependent: :destroy
end
在我的一个控制器中,我有一个调用来查找属于某个项目的所有访问权限,然后选择该访问权限集合的所有通知。但我有点麻烦。我认为像AccessPermission.where(project_id: 1).notifications 这样的电话会起作用,但事实并非如此。所以我求助于使用.map在ruby 中执行此操作
if AccessPermission.where(project_id: 1).map(&:notifications).include?(Notification.where(recipient_id: 1))
#Here is where I need help. Find the notification record in the ActiveRecord::Associations that made the call above "True." I tried:
notification = AccessPermission.where(project_id: 1).map(&:notifications).find(Notification.where(recipient_id: 1)).first
## That did not work, it returns an enumerator and then selects the very first object of the array no matter what the recipient_id is
else
#create the notification if no notification exists
access_permission.create_notification(recipient_id: 1)
end
【问题讨论】:
-
我很确定这也是一种糟糕的查找记录的方法,而且根本无法扩展。如果有人有更好的方法来帮助我在 SQL 中进行此调用,那可能会更好
标签: sql ruby-on-rails activerecord