如何为has_many关系编写Rails finder查询?

问题描述 投票:1回答:1

我正在使用Rails5。我有以下课程

class ParentObject < ApplicationRecord
    has_and_belongs_to_many :child_objects, :optional => false
end

我有一个参数params[:child_objects]传递到我的控制器中,该参数是这些对象ID的数组。如何编写查找程序以返回绑定到这些ID的对象?我尝试过此

parent_objects = ParentObject.joins(:child_objects).where(
  :child_objects => child_objects
)

但出现此错误

Unknown primary key for table parent_objects_child_objects in model ParentObject::HABTM_ChildObjects
ruby-on-rails ruby-on-rails-5 has-many finder
1个回答
2
投票

您可以在下面的查询中找到这些寄存器

ParentObject.joins(:child_objects).where('child_objects.id in (?)', child_objects)

其中('(?)中的'child_objects.id',child_objects)#您正在将id搜索到child_objects表中。指定联接表child_objects.id

这是相同的查询,但更多的是RailsWay。相同的想法

ParentObject.joins(:child_objects).where(child_objects: { id: child_objects} )
© www.soinside.com 2019 - 2024. All rights reserved.