Taylor Mitchell
Taylor Mitchell

Reputation: 613

Find rails model instances where `belongs_to` model instances were created in the last 24 hours

I'm not sure if I am wording this correctly or not.

I have two models store_attachments and store.

The store_attachments belongs_to store, but store has_many attachments.

The store_attachments have a created_at field.

I have a scope to find the store_attachments that were created in the last 24 hours, but I cannot seem to call it on the store model.

I currently have Store.store_attachments.added_within 24.hours.ago.

I see really why that one doesn't work, but I'm not really sure how I would figure that out. Store_attachments must belong to a Store, so it's not used anywhere else.

My code for the scope...

scope :added_within, lambda { |time_ago| { :conditions => ['created_at < ?', time_ago] } }

Upvotes: 1

Views: 25

Answers (1)

Erik
Erik

Reputation: 302

I think if you're passing in the date from 24 hours ago, you'd want the following conditional:

scope :added_within, lambda { |time_ago| { :conditions => ['created_at > ?', time_ago] } }

You had a <, which would mean older than the time you passed into the scope.

Also, you would need an instance of the Store class before using the relation, so you'd need

store = Store.first
store.store_attachments.added_within 24.hours.ago

I've always used a regular old class method instead of scopes. It just seems more readable to me.

class StoreAttachments < ActiveRecord::Base

  def self.added_within(time_ago = 24.hours.ago)
    where("created_at > ?", time_ago)
  end

  # vs

  scope :added_within, lambda { |time_ago| { conditions: [ 'created_at > ?', time_ago] } }
end

Upvotes: 2

Related Questions