Query Documents by ID or UID with Ruby

You can retrieve either multiple documents or a single one by their document ID or UID.

Query a document by ID

We've created a helper function that makes it easy to query by ID, but it is also possible to do this without the helper function.

getByID helper function

Here is an example that shows how to query a document by its ID using the getByID helper function.

Copy
document = api.getByID("WAjgAygABN3B0a-a")
# document contains the document content

Without the helper function

Here we perform the same query for a document by its ID without using the helper function.

Copy
response = api.query(Prismic::Predicates.at("document.id", "WAjgAygAAN3B0a-a"))
# response.results[0] contains the document content

Query multiple documents by IDs

We've created a helper function that makes it easy to query multiple documents by IDs.

getByIDs helper function

Here is an example of querying multiple documents by their ids using the getByIDs helper function.

Copy
ids = [ "WAjgAygAAN3B0a-a", "WC7GECUAAHBHQd-Y", "WEE_gikAAC2feA-z" ]
response = api.getByIDs(ids)
# response is the response object, response.results holds the documents

Without the helper function

Here is an example of how to perform the same query as above, but this time without using the helper function.

Copy
ids = [ "WAjgAygAAN3B0a-a", "WC7GECUAAHBHQd-Y", "WEE_gikAAC2feA-z" ]
response = api.query(Prismic::Predicates.in("document.id", ids))
# response is the response object, response.results holds the documents

Query a document by its UID

If you have added the UID field to a custom type, you can query a document by its UID.

getByUID helper function

Here is an example showing how to query a document of the type "page" by its UID "about-us" using the getByUID helper function.

Copy
document = api.getByUID("page", "about-us")
# document contains the document content

Without the helper function

Here is an example of the same query without using the helper function. It will query the document of the type "page" that contains the UID "about us".

Copy
response = api.query(Prismic::Predicates.at("my.page.uid", "about-us"))
# response.results[0] contains the document content