Thomas Taylor
Thomas Taylor

Reputation: 874

Active record select query to where and joins query

I currently have the following Active Record .select query being utilised in one of my controllers:

@bids = current_user.bids.select { |bid| !bid.bid_has_failed_date }

and the bid_has_failed_date method in my Bid model for the condition:

def bid_has_failed_date
  self.real_property_sale.try(:real_property_sale_project).try(:failed_date).present?
end 

I would prefer to use .where and .joins to do the same thing. So far I've got this:

.where(agent_id: agent_id).joins(real_property_sale: :real_property_sale_project).where(real_property_sale_projects: { failed_date: nil })

The problem with this is that it will only return a bid that has real_property_sale_project and a failed_date of nil. Instead I need it to return all bids excluding those where failed_date is present.

Upvotes: 2

Views: 50

Answers (1)

Andrey Deineko
Andrey Deineko

Reputation: 52357

where(agent_id: agent_id) - 
  where(agent_id: agent_id)
   .joins(real_property_sale: :real_property_sale_project)
    .where.not(real_property_sale_projects: { failed_date: nil })

Upvotes: 1

Related Questions