Neil
Neil

Reputation: 5178

ActiveRecord: Scope for where attribute is present

I want to grab those Blogs where its title.present? == true. (Blogs have a string attribute of title).

class Blog < ActiveRecord::Base
  scope :with_present_titles, -> {where("#{title.present?} == ?", true)} #doesn't work
end

@blogs = Blog.with_present_titles #doesn't work

Not sure what I'm doing wrong here.

Upvotes: 1

Views: 3538

Answers (3)

engineersmnky
engineersmnky

Reputation: 29308

Depending on your rails version you can also use where.not (introduced in rails 4) E.g.

scope :with_present_titles, ->{where.not(title: [nil,'']) }
#Blog.with_present_titles.to_sql
#=> "SELECT [blogs].* 
#    FROM [blogs] 
#    WHERE (NOT (([blogs].[title] = '' OR [blogs].[title] IS NULL)))"

Upvotes: 3

Sajid Rabbani
Sajid Rabbani

Reputation: 401

Simply write the following scope.

scope :with_present_titles, -> { where('title IS NOT ? AND TITLE != ?', nil, '') }

Upvotes: 1

vee
vee

Reputation: 38645

To return all records with some values in title column, you would update your scope with the following query:

scope :with_present_titles, -> { where("title is not null and title != ''") }

This returns all records with some value in title column leaving any null and empty titles.

.present? being a method provided by rails, you cannot simply use these methods in your DB queries.

Upvotes: 3

Related Questions