【问题标题】:How do you write a Rails finder query for a has_many relation?你如何为 has_many 关系编写 Rails finder 查询?
【发布时间】:2019-10-03 22:13:14
【问题描述】:

我正在使用 Rails 5。我有以下课程

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

    您可以通过下面的查询找到这些寄存器

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

    where('child_objects.id in (?)', child_objects) # 您正在将 id 搜索到 child_objects 表中。指定连接表child_objects.id

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

    ParentObject.joins(:child_objects).where(child_objects: { id: child_objects} )
    

    【讨论】:

      【解决方案2】:

      根据定义的类,has_and_belongs_to_many 表示一个父级可以有多个子级,一个子级也可以属于多个父级。这符合多对多关系的条件,因此需要一个关联(或联结)表。

      对于上面定义的类,rails 将查找child_objects_parent_objects,如果表不存在则引发错误。添加如下定义的联结表

      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;
      

      然后下面的查询将为给定的子对象(params[:child_objects])返回父对象

      ParentObject.joins(:child_objects).where(child_objects: { id: child_object_ids})
      

      但是,如果您希望孩子仅属于 1 个父母,则不需要定义 has_many 关系和联结表。

      class ParentObject < ApplicationRecord
        has_many :child_objects
      end
      
      ParentObject.joins(:child_objects).where(child_objects: { id: child_object_ids})
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多