Haisano
Haisano

Reputation: 21

Rails/ActiveRecord: Get a record made *AFTER* a particular date

So currently I have an issue where I am populating a database from xml files through my client's API. Each record has an expiration date in it, with the following format:

<offer_ends_at>2010-10-20T07:59:59-04:00</offer_ends_at>

Now, I need to run a query where I only get records that have an expiration in the future. My current code is:

@deals = Deal.where(["city = :city AND status = 'live' AND DATETIME(date_expires) >= DATETIME(:time)", { :city => @city.id, :time => Time.now }])

And when I'm making the record, I use this:

@deal.date_expires = DateTime.parse((entry/"offer_ends_at").inner_html)

And that is how I get the datetime and format it.

Here's where I'm at:

  1. I can't seem to get the date to go straight into the database with no issues. If I use the code above and have the schema set to have a column type of :datetime or :time, it gives me the date of 2000-01-01 and no valid time. It literally does not set an actual date anything like what it was given.
  2. I converted the column type to :string and tried using that. Now I can input the date properly (its a string) but at the same time, I can't get the query above to work.

I just need to make sure that I only show records that have not expired. After two days of scouring the net and no working answers, I decided to ask here. Thanks in advance :)

Upvotes: 1

Views: 1027

Answers (2)

nibbex
nibbex

Reputation: 361

ActiveRecord is built ontop of the Arel library so we can use that to make a more explicit query.

t = Deal.arel_table @deals = Deal.where(city: @city.id, t[:time].gt(1.second.ago))

This should get all deals in the future.

Upvotes: 0

Haisano
Haisano

Reputation: 21

The answer is that my code wasn't actually bad by the look of things. The issue that cropped up was that I had not properly formatted the input date to be something the could be understood when running the query. Simply changing my query from Time.now to Time.now.parse worked.

Upvotes: 1

Related Questions