Save 36% for Black Friday! Learn more

New Discussion

Notifications

You’re not receiving notifications from this thread.

How do I do the following in a better way?

3
Tips

How can I write the following code in better way

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

Hmm maybe

articles = Article.where(category: params[:category])
articles = articles.where(author_id: 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] = author.id if author
Article.find(:all, conditions: conditions)

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

Join the discussion
Create an account Log in