All threads / How do I do the following in a better way?

Ask A Question


You’re not receiving notifications from this thread.

How do I do the following in a better way?

teja asked in Tips

How can I write the following code in better way

if author.present?
    Article.where(category:  params[:category], author_id:
    Article.where(category:  params[:category])

Hmm maybe

articles = Article.where(category: params[:category])
articles = articles.where(author_id: if author.present?

# use your articles here...

You could build the conditions first then use them in the query:

conditions = { category: params[:category] }
conditions[:author_id] = if author
Article.find(:all, conditions: conditions)
Join the discussion

Want to stay up-to-date with Ruby on Rails?

Join 53,130+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    logo Created with Sketch.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2021 GoRails, LLC. All rights reserved.