mirror of
https://github.com/chatwoot/chatwoot.git
synced 2026-07-07 21:14:32 +08:00
The system determines a user’s active account by checking the
`active_at` field in the `account_users` table and selecting the most
recently active account:
```ruby
def active_account_user
account_users.order(active_at: :desc)&.first
end
```
This works fine when all accounts have a valid active_at timestamp.
**Problem**
When a user is added to a new account, the `active_at` value is NULL
(because the account has never been explicitly activated). Ordering by
active_at DESC produces inconsistent results across databases, since
handling of NULL values differs (sometimes treated as high, sometimes
low).
As a result:
- Mobile apps (critical impact): `/profile` returns the wrong account.
The UI keeps showing the old account even after switching, and
restarting does not fix it.
- Web app (accidentally works): Appears correct because the active
account is inferred from the browser URL, but the backend API is still
wrong.
**Root Cause**
- The ordering logic did not account for NULL `active_at`.
- New accounts without active_at sometimes get incorrectly prioritized
as the “active” account.
**Solution**
Explicitly ensure that accounts with NULL active_at are sorted after
accounts with real timestamps by using NULLS LAST:
```ruby
def active_account_user
account_users.order(Arel.sql('active_at DESC NULLS LAST, id DESC'))&.first
end
```
- Accounts with actual `active_at` values will always be prioritized.
- New accounts (with NULL active_at) will be placed at the bottom until
the user explicitly activates them.
- Adding id DESC as a secondary ordering ensures consistent tie-breaking
when multiple accounts have the same `active_at`.
|
||
|---|---|---|
| .. | ||
| channel | ||
| concerns | ||
| enterprise/audit | ||
| integrations | ||
| .keep | ||
| account_spec.rb | ||
| account_user_spec.rb | ||
| agent_bot_inbox_spec.rb | ||
| agent_bot_spec.rb | ||
| article_spec.rb | ||
| assignment_policy_spec.rb | ||
| attachment_spec.rb | ||
| automation_rule_spec.rb | ||
| campaign_spec.rb | ||
| category_spec.rb | ||
| contact_inbox_spec.rb | ||
| contact_spec.rb | ||
| conversation_participants_spec.rb | ||
| conversation_spec.rb | ||
| csat_survey_response_spec.rb | ||
| data_import_spec.rb | ||
| folder_spec.rb | ||
| inbox_member_spec.rb | ||
| inbox_spec.rb | ||
| installation_config_spec.rb | ||
| label_spec.rb | ||
| macro_spec.rb | ||
| mention_spec.rb | ||
| message_spec.rb | ||
| note_spec.rb | ||
| notification_setting_spec.rb | ||
| notification_spec.rb | ||
| platform_app_permissible_spec.rb | ||
| platform_app_spec.rb | ||
| portal_spec.rb | ||
| related_category_spec.rb | ||
| reporting_event_spec.rb | ||
| team_member_spec.rb | ||
| team_spec.rb | ||
| user_spec.rb | ||
| webhook_spec.rb | ||
| working_hour_spec.rb | ||