Overview
Rules are boolean expressions associated with collection operations (list, view, create, update, delete).
When to Use Rules
| Scenario | Example | ||
|---|---|---|---|
| Record ownership | created_by = @request.auth.id | ||
| Role-based access | @request.auth.role = "admin" | ||
| Status-based access | `status = “published” | @request.auth.role = “admin”` | |
| Pattern matching | email ~ "%@company.com" | ||
| Complex logic | `(priority > 5 && @request.auth.role = “manager”) | created_by = @request.auth.id` |
Rule Syntax
Basic Expressions
Logical Operators
| Operator | Usage | Description | ||||
|---|---|---|---|---|---|---|
&& | cond1 && cond2 | Both conditions must be true | ||||
| ` | ` | `cond1 | cond1` | At least one condition must be true | ||
! | !condition | Simple negation | ||||
() | `(c1 | c2) && c3` | Grouping for precedence |
() > ! > comparisons > && > ||
Evaluation Context
Rules have access to the following variables:1. @request.auth (Standard)
| Field | Description |
|---|---|
@request.auth.id | Current user ID |
@request.auth.email | Current user email |
@request.auth.role | Current user role |
@request.auth.account_id | Current account context |
2. @request.data (Action-specific)
Available during create and update operations.
@request.data.fieldname: Accesses the value being sent in the request body.
[email protected]_admin (Don’t allow setting admin flag via this route).
3. Record Fields (Direct Access)
You can reference any field in the record directly by name.created_bystatusyour_custom_field
Built-in Macros
| Macro | Description | Example |
|---|---|---|
@has_role(role) | User has specific role | @has_role("admin") |
@has_group(group) | User has specific group | @has_group("managers") |
@owns_record() | User is the creator | @owns_record() |
@is_creator() | Alias for @owns_record | @is_creator() |
Rule Examples
Example 1: Edit Own Drafts
Only allow editing if the user is the creator AND the status is “draft”.Example 2: Admin or Owner
Example 3: String Pattern Matching
Allow viewing only if the record type starts with “public”.Example 4: Complex Multi-Condition
Testing Rules
Manual Testing in Admin UI
SnackBase provides a built-in Rule Tester in the Collections settings:- Navigate to Collections -> Edit Collection -> Rules.
- Write your rule.
- Use the “Test Rule” button to simulate evaluation against a mock user and record.
API Testing
You can also test rules via the API:Best Practices
- Keep Rules Simple: Complex logic is hard to debug. Use SQL Macros for complex multi-table checks.
- Use Parentheses: Always group conditions in complex expressions to ensure correct evaluation order.
- Optimistic Rules: In SnackBase, rules are compiled to
WHEREclauses, so they are extremely fast. - Deny by Default: If no rule is defined for an operation, access is denied.