Select <ActiveRecord::Associations::CollectionProxy> 中的正确记录
Select the correct record in an <ActiveRecord::Associations::CollectionProxy>
我想了解我在这里做错了什么 - 如果有人能给我指出正确的方向,那就太好了!
我的申请中有以下关联:
class Notification < ApplicationRecord
belongs_to :notificationable, polymorphic: true
end
class AccessPermission < ApplicationRecord
belongs_to :project
has_many :notifications, as: :notificationable, dependent: :destroy
end
在我的一个控制器中,我有一个调用可以找到属于一个项目的所有访问权限,然后 select 该访问权限集合的所有通知。但是我有点麻烦。我认为像 AccessPermission.where(project_id: 1).notifications
这样的调用会起作用,但它不起作用。所以我在 ruby 中使用 .map
来做这个
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
你想要一个 has_many 通过项目模型的关系。
类似于:
has_many :notifications, through: :access_permissions
那你就可以了
project.notifications
得到你想要的。应该很好地扩展,它会加入查询的表。
完成后,您可以执行以下操作:
project = Project.find(1)
if (notification = project.notifications.find_by(recipient_id: 1))
# Do something with your notification here
else
access_permission.create_notification(recipient_id: 1)
end
我想了解我在这里做错了什么 - 如果有人能给我指出正确的方向,那就太好了!
我的申请中有以下关联:
class Notification < ApplicationRecord
belongs_to :notificationable, polymorphic: true
end
class AccessPermission < ApplicationRecord
belongs_to :project
has_many :notifications, as: :notificationable, dependent: :destroy
end
在我的一个控制器中,我有一个调用可以找到属于一个项目的所有访问权限,然后 select 该访问权限集合的所有通知。但是我有点麻烦。我认为像 AccessPermission.where(project_id: 1).notifications
这样的调用会起作用,但它不起作用。所以我在 ruby 中使用 .map
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
你想要一个 has_many 通过项目模型的关系。
类似于:
has_many :notifications, through: :access_permissions
那你就可以了
project.notifications
得到你想要的。应该很好地扩展,它会加入查询的表。
完成后,您可以执行以下操作:
project = Project.find(1)
if (notification = project.notifications.find_by(recipient_id: 1))
# Do something with your notification here
else
access_permission.create_notification(recipient_id: 1)
end