Create new or get existing association in Ecto

I have a User that has_one StripeProfile association. I store the stripe details there and for any place I need the stripe information I can preload the :stripe_profile association with it. The issue is I already have a couple of authors in my system, so for them when I preload the StripeProfile association, it returns nil. I want it to return an empty association associated with the user. How do I achieve this without checking whether the association exists everytime I use it ?

Can you submit a DB query directly like

INSERT INTO stripe_profiles VALUES (user_id, empty_stripe_info...);

for each of these pre-existing users?

Is running this in production db safe, or should I put it inside the migration ?

I think it is safe because you’re not changing the table, just adding some rows. If you really want the ability to rollback with Ecto migrations, you could probably use Migration.execute/2, but I don’t think that this is a “migration” case, since the table is not changing.

1 Like

Can you point out the SQL migration too, I can’t seem to figure out how to write the query to get all the Users that does not have an associated StripeProfile.

Since you said you only have “a couple” authors, I expected you would just inspect the tables and insert manually one at a time.

If, on the other hand, you have thousands of cases like this, and you need to put together a single query for all of them, you’ll probably want to do something like

  • full join between the users and stripe_profiles
  • select only the users where some stripe-related column = NULL
  • Use Enum.map/2 to insert each user’s id along with the default stripe info