Sql 在<;ActiveRecord::Associations::CollectionProxy>;

Sql 在<;ActiveRecord::Associations::CollectionProxy>;,sql,ruby-on-rails,activerecord,Sql,Ruby On Rails,Activerecord,我正在努力理解我做错了什么——如果有人能给我指出正确的方向,那就太好了 我的申请中有以下关联: class Notification < ApplicationRecord belongs_to :notificationable, polymorphic: true end class AccessPermission < ApplicationRecord belongs_to :project has_many :notifications, as:

我正在努力理解我做错了什么——如果有人能给我指出正确的方向,那就太好了

我的申请中有以下关联:

class Notification < ApplicationRecord
    belongs_to :notificationable, polymorphic: true
end


class AccessPermission < ApplicationRecord
    belongs_to :project
    has_many :notifications, as: :notificationable, dependent: :destroy
end


你想在你的项目模型上建立一个多方面的关系

比如:

  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 :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

我很确定这也是一种很糟糕的找到记录的方法,而且根本无法扩展。如果有人有更好的方法来帮助我在SQL中进行此调用,这可能是更好的方法。我很确定这也是一种查找记录的糟糕方法,而且根本不会扩展。如果有人有更好的方法来帮助我在SQL中进行此调用,那么这可能是更好的方法。谢谢你提醒我你已经很多次通过了!我将notifications.find更改为notifications.find_by call,这应该更快,并且避免在Ruby.Spot中循环。谢谢你提醒我你已经很多次通过了!我将notifications.find更改为notifications.find_by call,这应该更快,并且避免在Ruby中循环。