嗨,我想知道在Rails 6中的多对多关系中进行下一个查询的最佳方法是什么。
这是我的结构:
class Contact < ApplicationRecord has_and_belongs_to_many :lists end class List < ApplicationRecord has_and_belongs_to_many :contacts end
这是迁移文件:
class AddContactsListsRelation < ActiveRecord::Migration[6.0] def change create_table :contacts_lists do |t| t.belongs_to :contact t.belongs_to :list end end end
这是我的查询:
class ContactsLists < ApplicationRecord def self.find_with_page(listId, paginationQuery) contacts = List.find(listId).contacts result = contacts.order(created_at: paginationQuery[:order]).limit(paginationQuery[:page_size]) .offset(paginationQuery[:page_number] * paginationQuery[:page_size]) result end end
我觉得这是次优的方式(我在做两个不同的查询,对吗?但是我不是Rails查询API的专家。
嗨,我想知道在Rails 6中的多对多关系中进行下一个查询的最佳方法是什么。这是我的结构:类Contact
Contact
.joins(:lists)
.where(list_id: listId)
.order(created_at: paginationQuery[:order]
.limit(paginationQuery[:page_size])
.offset(paginationQuery[:page_number] * paginationQuery[:page_size])