0

I am trying to check if a record is stale and update if it is. Here's my code:

  @listing = Listing.where(listing_id: listing['listing_id'])
  if @listing.exists?
    if @listing.created_at < 7.days.ago # line where error shows
      @listing.update(state: listing['state'])
    end
  end

And I'm getting the following error:

undefined method `updated_at' for #<Listing::ActiveRecord_Relation:0x00007fb3ebabbac0> Did you mean? update_all

Here's my DB record:

<Listing id: 5, listing_id: 188996174, state: "active", created_at: "2018-03-13 20:43:35", updated_at: "2018-03-13 20:46:48">

And my migration:

class CreateListings < ActiveRecord::Migration[5.1]
  def change
    create_table :listings do |t|
      t.integer :listing_id
      t.string :state

      t.timestamps
    end
  end
end

Any ideas? Thanks in advance!

Ben
  • 5,030
  • 6
  • 53
  • 94
Maayan Naveh
  • 340
  • 3
  • 20

1 Answers1

1

using where, you get an ActiveRecord_Relation :

@listing = Listing.where(listing_id: listing['listing_id'])

You want an single object here.

I am unsure about exactly how you've set things, but assuming the listing_id column is unique, the following should do the job :

@listing = Listing.find_by(listing_id: listing['listing_id'])

the the rest of your code is okay. As it would only return the first object matching the listing-id. So then you could try to call updated_at on this object

If they're not unique, you might want to do the following :

@listings = Listing.where(listing_id: params['listing_id'])
@listings.each do |listing|
  listing.update(state: params['state']) if listing.created_at < 7.days.ago
end

Or shorter :

Listing
  .where(
    'listing_id = ? AND updated_at > ?',
    params['listing_id'],
    Time.zone.now - 7.days
  )
  .update_all(state: params['state'])
Ben
  • 5,030
  • 6
  • 53
  • 94
  • 1
    The answer is almost true except the fact that, the return value of `where` is not an array. It's an instance of `ActiveRecord_Relation`. – Foo Bar Zoo Mar 13 '18 at 21:33
  • that's innacurate you're right (found a decent explanation here https://stackoverflow.com/a/38326002/102133) That is, you can loop on it, which was my point. edited the answer – Ben Mar 13 '18 at 21:43
  • We call these kind of objects as `Enumerable`. Thanks for updating the answer. – Foo Bar Zoo Mar 13 '18 at 21:49
  • Thank you so much, that works perfectly! Listing ID is unique so I can take the shorter path. – Maayan Naveh Mar 14 '18 at 07:00