【问题标题】:Select the correct record in an <ActiveRecord::Associations::CollectionProxy>在 <ActiveRecord::Associations::CollectionProxy> 中选择正确的记录
【发布时间】: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


【解决方案1】:

您希望在您的项目模型上有一个 has_many through 关系。

类似:

  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

【讨论】:

  • 正确。感谢您对 has_many through 的提醒!
  • 我将 notifications.find 更改为 notifications.find_by 调用,它应该更快并且避免在 Ruby 中循环。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-18
  • 2014-04-26
相关资源
最近更新 更多