> ## Documentation Index
> Fetch the complete documentation index at: https://sequin.io/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Upsert to Postgres (Ruby/Rails)

> One of the most popular destinations for API data is Postgres. Sequin makes it easy to sync API data to Postgres so you can read your data at rest.

[Read more about upserting to Postgres](/how-to/upsert-to-postgres).

[Active Record](https://guides.rubyonrails.org/active_record_basics.html) is the most popular ORM for Ruby and the default ORM that ships with Ruby on Rails.

To handle Sequin records using ActiveRecord, first set up your models like this:

```ruby theme={null}
class Subscription < ApplicationRecord
  self.table_name = 'subscriptions'
end

class SequinRecord
  attr_reader :id, :upstream_id, :collection_id, :data, :deleted, :inserted_at, :provider, :stream_id, :sync, :updated_idx, :upstream_created_at, :upstream_updated_at

  def initialize(attributes)
    @id = attributes[:id]
    @upstream_id = attributes[:upstream_id]
    @collection_id = attributes[:collection_id]
    @data = attributes[:data]
    @deleted = attributes[:deleted]
    @inserted_at = attributes[:inserted_at]
    @provider = attributes[:provider]
    @stream_id = attributes[:stream_id]
    @sync = attributes[:sync]
    @updated_idx = attributes[:updated_idx]
    @upstream_created_at = attributes[:upstream_created_at]
    @upstream_updated_at = attributes[:upstream_updated_at]
  end
end
```

Then you can upsert records like this:

```ruby theme={null}
class StripeSyncService
  def self.process_record(record)
    case record.collection_id
    when "stripe:subscription"
      attributes = {
        id: record.id,
        upstream_id: record.upstream_id,
        stripe_customer_id: record.data['stripe_customer_id'],
        plan_id: record.data['plan_id'],
        quantity: record.data['quantity'],
        internal_id: record.sync["external_id"],
        updated_idx: record.updated_idx,
        upstream_created_at: record.upstream_created_at,
        upstream_updated_at: record.upstream_updated_at
      }
      # Upsert the record
      Subscription.upsert(attributes, unique_by: :id)
    when "stripe:customer"
      # handle upserts to other collections/tables
    end
  end
end
```
