我正在使用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
您可以在下面的查询中找到这些寄存器
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} )