Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to compare created_at reliably for Rails Activerecords
    primarykey
    data
    text
    <p>Basically, my query is saying that a record's created_at is greater than its own created_at.</p> <pre><code>irb(main):025:0&gt; u = User.first User Load (1.0ms) SELECT "users".* FROM "users" LIMIT 1 =&gt; #&lt;User id: 1, email: "my@email.com", encrypted_password: "stuff...", created_at: "2012-02-01 18:56:45", updated_at: "2012-03-17 21:10:13"&gt; irb(main):026:0&gt; User.where("created_at &gt; ?", u.created_at).include? u User Load (1.0ms) SELECT "users".* FROM "users" WHERE (created_at &gt; '2012-02- 01 18:56:45.740392') =&gt; true </code></pre> <p>The query shown makes it clear that it's a datetime formatting issue...when it builds the query it's rounding the fractions of a second. <strong>Can I modify the query to get it to order by created_at predictably/consistently?</strong> </p> <p>I've poked around some other questions that discuss ActiveRecord precision and suggest strftime, etc., but I can't get it to work reliably. I'm using SQLite in dev (my console quote above) and Postgres in production.</p> <p>Note: The broader goal here is to add <code>#next</code> and <code>#previous methods</code> to most/all of my resources so I can iterate through them more easily in my admin menus. If there's another way to achieve a default order that's reliable I'm open to it.</p> <p>Both methods work properly as coded below when I pass non-timestamp arguments like <code>:name</code>, but <code>#next</code> returns the same object if I pass no argument (defaulting to <code>:created_at</code>)</p> <pre><code>def previous(column = :created_at) self.class.first(:conditions =&gt; ["#{column} &lt; ?", self.send(column)], :order =&gt; "#{column} desc") end def next(column = :created_at) self.class.first(:conditions =&gt; ["#{column} &gt; ?", self.send(column)], :order =&gt; "#{column} asc") end </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload