[英]How do you write a Rails finder query for a has_many relation?
I'm using Rails 5. I have the following class我正在使用 Rails 5。我有以下 class
class ParentObject < ApplicationRecord
has_and_belongs_to_many :child_objects, :optional => false
end
I have a parameter, params[:child_objects]
, passed in to my controller that is an array of those objects' IDs.我有一个参数
params[:child_objects]
,传递给我的 controller ,它是这些对象 ID 的数组。 How can I write a finder to return objects tied to those IDs?我如何编写一个查找器来返回与这些 ID 相关的对象? I tried this
我试过这个
parent_objects = ParentObject.joins(:child_objects).where(
:child_objects => child_objects
)
but got this error但收到此错误
Unknown primary key for table parent_objects_child_objects in model ParentObject::HABTM_ChildObjects
You can find these registers with this query bellow您可以通过以下查询找到这些寄存器
ParentObject.joins(:child_objects).where('child_objects.id in (?)', child_objects)
where('child_objects.id in (?)', child_objects) # you are searching ids into child_objects table.
where('child_objects.id in (?)', child_objects) # 您正在将 id 搜索到 child_objects 表中。 Specify the join table
child_objects.id
指定连接表
child_objects.id
This is the same query, but more RailsWay.这是相同的查询,但更多的是 RailsWay。 Same idea
相同的想法
ParentObject.joins(:child_objects).where(child_objects: { id: child_objects} )
Based on the classes defined, has_and_belongs_to_many
means a parent can have many children, as well as a child, can belong to many parents.根据定义的类,
has_and_belongs_to_many
意味着一个父母可以有很多孩子,就像一个孩子可以属于很多父母一样。 This qualifies for a many to many relation and thus needs an associative (or junction) table.这符合多对多关系的条件,因此需要一个关联(或联结)表。
For above-defined classes, rails will look for child_objects_parent_objects
and raise error if table not present.对于上面定义的类,rails 将查找
child_objects_parent_objects
并在 table 不存在时引发错误。 Add a junction table as defined below添加如下定义的联结表
CREATE TABLE `child_objects_parent_objects` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`parent_object_id` int(11) NOT NULL,
`child_object_id` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ROW_FORMAT=DYNAMIC;
And then the below query will return parent objects for the given child objects( params[:child_objects]
).然后下面的查询将返回给定子对象的父对象(
params[:child_objects]
)。
ParentObject.joins(:child_objects).where(child_objects: { id: child_object_ids})
However, If you want a child to belong to only 1 parent then define a has_many
relation & junction table will not be required.但是,如果您希望孩子只属于 1 个父母,则不需要定义
has_many
关系和联结表。
class ParentObject < ApplicationRecord
has_many :child_objects
end
ParentObject.joins(:child_objects).where(child_objects: { id: child_object_ids})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.