Home Select expired and not expired values MySQL, Rails 5
Reply: 1

Select expired and not expired values MySQL, Rails 5

gdfgdfg
1#
gdfgdfg Published in 2018-01-06 16:27:14Z

I have an Ruby on Rails 5 app with MySQL as database. I have table products and table subscriptions with the standard Rails 5 datetime column - created_at'.

The model Product has_many :subscriptions and the model Subscription belongs_to :product.

I want to select all subscriptions for a product that are created before for the example 1 day and all products that are created (for the example last 24 hours) in this way that I can use them like this - product.expired_subscriptions and product.active_subscriptions.

fool-dev
2#
fool-dev Reply to 2018-01-06 18:06:30Z

Try to the following

#=> subscription.rb
scope :expired_subscriptions, -> { where("created_at >= ?", 24.hours.ago) }
scope :active_subscriptions, -> { where(created_at: (Time.now - 24 .hours)..Time.now) }

and then

@product = Product.find(1) #=> find product by ID
@product.subscriptions.expired_subscriptions #=> all  subscriptions > 24 hours
#=============#
@product = Product.find(1) #=> find product by ID
@product.subscriptions.active_subscriptions #=> all subscriptions within 24 hours

Hope to help

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.307062 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO