zauzaj
zauzaj

Reputation: 1226

Sql is null in ActiveRecord query

I have class method to get posts but now sure how to resolve it.

So, somebody can set flag on post, but in meantime post doesn't have any flag :

Post.find(3).flag #nil

This is self method for getting posts :

 def self.for_review
   joins(:flag).where('need_approval = ? and question = ? and DATE(posts.created_at) =   ?', "true", "false", Time.now.to_date)
 .where('flags.need_check = ? or flags IS NULL', 'false')
 end

Problem is with second where condition

where('flags.need_check = ? or flag IS NULL', 'false')

Because flag is NULL doesn't work .

Is anybody knows what's problem ? Thanks

Upvotes: 2

Views: 539

Answers (2)

Thilo
Thilo

Reputation: 17735

joins uses an INNER JOIN by default; this will only return posts that do have at least one flag. You need a LEFT JOIN. Assuming a Post has_many flags:

joins('LEFT JOIN flags ON posts.id = flags.post_id').where(...).where('flags.need_check = ? OR flags.id IS NULL', false)

Also drop the quotes around true and false, unless those fields are indeed strings with the literal values "true" and "false".

Upvotes: 1

BroiSatse
BroiSatse

Reputation: 44685

THe problem is joins(:flag). It defaults to inner join, so all the posts without flags will be rejected. You need includes(:flag).references(:flag) instead.

Also flags IS NULL makes no sense as there is no column called flags. Instead do flags.id IS NULL

Upvotes: 1

Related Questions