Table of contentsClick link to navigate to the desired location
This content has been automatically translated from Ukrainian.
PostgreSQL has a powerful but often underestimated feature - Row Level Security (RLS). In short, it is data protection at the row level of the table, meaning the system determines which records the user can see or modify before the query even reaches your Rails code.
How it works
In a typical situation, access to data is controlled in the application — for example, in Rails we write:
@posts = Post.where(user_id: current_user.id)
But RLS allows you to delegate this check to the database itself. You enable the security policy for the table:
ALTER TABLE posts ENABLE ROW LEVEL SECURITY;
CREATE POLICY user_is_owner
ON posts
FOR SELECT USING (user_id = current_setting('app.current_user_id')::int);
After this, even if someone does SELECT * FROM posts, PostgreSQL will automatically apply the condition so that the user sees only their rows.
How to integrate RLS in Rails
In Rails, you can set current_user.id in the database context before executing the query:
ActiveRecord::Base.connection.execute("SET app.current_user_id = #{current_user.id}")
Then all queries (Post.all, Post.find, even joins) will return only allowed data - without additional where in the code.
This is convenient for multi-user systems, SaaS, or APIs, where security should not rely solely on the application level.
Why is this even necessary
- Database-level security — even if someone accidentally forgets where(user_id: ...), the data will not leak.
- Simplicity of queries — you can write Model.all without thinking about filters.
- Unified access control — rules are stored together with the data, not scattered across controllers and services.
RLS does not replace authorization in the application. It is an additional layer of protection that ensures that even at a low level no one gets "extra" data. Row Level Security is like where(user_id: current_user.id), but built into the database itself.
This post doesn't have any additions from the author yet.