Search code examples
ruby-on-railsrubypostgresqlmany-to-many

How to correctly do a many to many query in Rails 6


What is the best way to do the next query in an many-to-many relation in Rails 6.

This is my structure:

class Contact < ApplicationRecord
  has_and_belongs_to_many :lists
end

class List < ApplicationRecord    
  has_and_belongs_to_many :contacts
end

This is the migration file:

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

And this is my query:

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

I am not expert on the Rails query API but I think this is a suboptimal way to do two different querys, right?


Solution

  • Since you have defined the many-to-many relationship, you can easily join the tables.

    You need to get contacts, which should be the "base" model to build your query, for example:

    Contact
      .joins(:lists)
      .where(list_id: listId)
      .order(created_at: paginationQuery[:order]
      .limit(paginationQuery[:page_size])
      .offset(paginationQuery[:page_number] * paginationQuery[:page_size])