0

The premise of my question is simple, I have three tables :

  • users (user_id)
  • records_users (record_id, user_id)
  • records (record_id, created_by)

I would like users to be able to INSERT into the records_users table only if their id (column user_id from the users table) is in the created_by field of the records table.

In other words : I would like users to only be able to insert rows for which the record_id is an actual record that is tied to them in the record table through the created_by field.

What I have tried :

  • Have looked through RLS options but I cannot seem to find how to integrate a condition based on what is being inserted. Does something like this exist ?

     CREATE POLICY "Enable insert on linked records"
     ON public.records_users
         FOR INSERT USING (
           record_id_being_inserted IN (SELECT record_id FROM records WHERE created_by                 = auth.uid()) 
         );
    
  • I have created an RPC Postgres function which applies that logic, but it is blocked by the RLS policies applied to the records_users table and I do not wish to open inserts to all users without having this logic mandatory.

Any help would be appreciated.

2
  • 1
    I'm a little confused by your What I have tried section, the example you gave of a RLS, have you tried it? you would change record_id_being_inserted to the column name in the records_users table. Commented Aug 13, 2023 at 18:30
  • Yes, actually you are right. I gave it another shot and referencing the inserted column actually does work simply enough. I think the previous query on which I had tried that had the record_ids confused which caused it not to work initially. Thank you for your help Commented Aug 14, 2023 at 10:06

1 Answer 1

0

As stated by @andrew smith, the answer was pretty straight forward. You can simply reference the fields inserted by using their column names. So for example :

 CREATE POLICY "Enable insert on linked records"
  ON public.records_users
      FOR INSERT USING (
   record_id_being_inserted IN (SELECT record_id FROM records WHERE created_by                 = auth.uid()) 
 );

This query would work if record_id_being_inserted is the name of the column field you want to check.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.