Back to blog

Blog

Dynamically Build Where Clauses in Ruby on Rails

How to build conditional Where queries of ActiveRecord and Mongoid

May 28, 2023 · database, ruby-on-rails, sql, activerecord, mongoid
Dynamically Build Where Clauses in Ruby on Rails
In Ruby on Rails, the default choice for object-relational mapping (ORM) is ActiveRecord, which provides an interface to interact with relational databases. ActiveRecord is widely used in Rails applications and offers a convenient way to define models, handle database operations, and establish relationships between different entities. On the other hand, Mongoid is an alternative ORM specifically designed for MongoDB, a NoSQL database. Mongoid provides a more object-oriented approach to working with MongoDB and allows developers to interact with the database using Ruby objects and queries. With both of these ORMs one difficult problem to tackle is to build queries with dynamic where clauses. Solution #1 — Not Recommended. @posts = Post.all@posts = @posts.where(published: params[:published]) if params[:published]@posts = @posts.where(author: params[:author]) if params[:author]@posts = @...

The full article is published on Medium.

Read on Medium