April 16, 2024, 11:45 a.m. | Dmitry Daw

DEV Community dev.to

I need to get a selection of users with an SQL query like this:



sql =<<~SQL
token IS NULL OR
(
token = 'some_token'
AND (
state = 'cancelled' AND created_at > ?
OR state = 'submitted'
)
)
SQL
User.where(sql, Time.now)


I don't like to have SQL in my queries — all hidden code in scopes is now pops up, and it is hard to compose.


But could I rewrite this query with ActiveRecord? Let's try:



User
.where(token: nil) …

chatgpt lies null postgres queries query rails ruby sql sql query state token

Data Architect

@ University of Texas at Austin | Austin, TX

Data ETL Engineer

@ University of Texas at Austin | Austin, TX

Lead GNSS Data Scientist

@ Lurra Systems | Melbourne

Senior Machine Learning Engineer (MLOps)

@ Promaton | Remote, Europe

#13721 - Data Engineer - AI Model Testing

@ Qualitest | Miami, Florida, United States

Elasticsearch Administrator

@ ManTech | 201BF - Customer Site, Chantilly, VA