ogelacinyc
ogelacinyc

Reputation: 1372

What is good way to query chaining conditionally in rails?

If I need to query conditionally, I try a way like this:

query = Model.find_something
query = query.where(condition1: true) if condition1 == true
query = query.where(condition2: true) if condition2 == true
query = query.where(condition3: true) if condition3 == true

It's work well. But I think that it is a way to repeat same code and a look is not good.

Is it possible query does not reassign to variable per every conditional expression? like this:

query.where!(condition1: true) # But it can not be in rails :)

I recently started as Rails5.

What else is the best way to do Rails5?

Upvotes: 1

Views: 277

Answers (1)

Vasilisa
Vasilisa

Reputation: 4640

You can use model scopes:

class Article < ApplicationRecord
  scope :by_title, ->(title) { where(title: title) if title }
  scope :by_author, ->(name) { where(author_name: name) if name }
end

Just chain scopes anywhere you need:

Article.by_title(params[:title]).by_author(params[:author_name])

If parameter present you get scoped articles, if there is no such parameter - you get all Articles

Upvotes: 4

Related Questions