undefined method `updated_at=' for ActiveRecord

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'])

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


Any ideas? Thanks in advance!

1 answer

  • answered 2018-03-13 21:22 Ben

    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

    Or shorter :

        'listing_id = ? AND updated_at > ?',
        Time.zone.now - 7.days
      .update_all(state: params['state'])