Rails object cannot list values where Boolean is true

286 views Asked by At

EDIT- This is now Solved. See bottom of post. Thx to Rob.W for pointing out that my default method was overriding everything, even when I tried to update the value

I cannot list all "Deals" in my database where the attribute 'settled' is set to true. As you will see in the below script from a rails console, I update an object to become true, rails confirms the update, but then after that the object still shows as false

I've tried all sorts of syntax, with or without "", etc, have looked at similar questions, but they dont solve my problem.

1) nothing showing true in the db:

[2] pry(main)> Deal.where(settled: true)
  ...
=> []

2) So i update one myself, and rails confirms

[3] pry(main)> Deal.find(73).update(settled: true)
...
=> true

3) Here is the weird part: a query for the deals with settled true returns the one I just created... but it shows as if it was false!

[4] pry(main)> Deal.where(settled: true)
  Deal Load (0.8ms)  SELECT "deals".* FROM "deals" WHERE "deals"."settled" = 't'
=> [#<Deal:0x007fad593dc468
  id: 73,
  amount: 45.0,
  description: "no description yet",
  settled: false,
  created_at: Wed, 10 Jun 2015 19:52:05 UTC +00:00,
  updated_at: Wed, 10 Jun 2015 21:14:36 UTC +00:00,
  payer_id: 55,
  receiver_id: 57>]

Note that in the deal.rb file for the Deal model, I have the below to give the default value of false to 'settled'

  def defaults
    self.description = 'no description yet'
    self.settled = 'false'
  end

EDIT - SOLUTION TO THE ISSUE 1) I deleted the default function as it prevented any further override. Instead i wrote a migration to add the default value, as per this very interesting thread How to set default values in Rails?

def change
    change_column :table_name, :column_name, :type, default: "Your value"
  end

2) The final trick is the syntax to query for the true values. Upon self.update(settled: true), rails gives the object the value "t", not true, not 'true' - as a result the right code for query is

@history = current_user.all_deals.select {|deal| deal.settled == 't'}.sort_by(&:created_at)

1

There are 1 answers

0
gperrin01 On

EDIT - SOLUTION TO THE ISSUE 1) I deleted the default function as it prevented any further override. Instead i wrote a migration to add the default value, as per this very interesting thread Correct Way to Set Default Values in Rails

def change
    change_column :table_name, :column_name, :type, default: "Your value"
end

2) The final trick is the syntax to query for the true values. Upon self.update(settled: true), rails gives the object the value "t", not true, not 'true' - as a result the right code for query is

@history = current_user.all_deals.select do |deal| 
  deal.settled == 't'
end.sort_by(&:created_at)