0

I am creating some Category in my rails app. I'd like to decide when the articles will be displayed based on the different peroids of time setting. I'm looking for a better way to do this, since I don't think that using gem whenever is needed under this circumstance.

The questions I would like to ask are:

1.how to set time period for Category
2.how to check the time period(maybe use between?) when conducting query,
3.all schedules can be displayed like a google calendar(use simple_calendar), the entire schedule will be showed in my backstage.

The solution I first come up with is to create two date column in Category and define begin time and end time.

Is there any better way to handle this? Is there any gem specifically for this purpose or this situation?

John
  • 387
  • 5
  • 17

1 Answers1

1

If I understand this correctly, a Category is a time period that a user can create dynamically. There will be some different Articles that will have a time period associated with them as well. The Articles will fall into a Category if the Articles's time falls within the start and end times of the Category. If this is the case the time period must have a start and end time. Something like the following:

# Category Class

class Category < ActiveRecord::Base
  # Omitting rest of the class..

  def articles_created_between(time_range)
    articles.where(created_at: time_range)
  end
end

You can then load a category:

category = Category.last

And find the articles in the category:

articles = category.articles_created_between((Time.now.midnight - 1.day)..Time.now.midnight)

See Ranged Conditions for some more information: http://guides.rubyonrails.org/active_record_querying.html#hash-conditions

jklina
  • 3,407
  • 27
  • 42
  • thanks, I restate the circumstance: 1.the relation between Category and Article is Category many to many. 2.Category have own image and title, so website show image and title as an section, then user can click photo to enter an page fill with articles in this category. so begin/end time is on category. 3.does every time I query for category to check time is a stupid way?or increase loading for server? – John Apr 12 '16 at 02:43
  • I've updated my answer to add a method to the `Category` model that will let you filter by a specified time range. Checking the time for each query is a perfectly normal operation and I don't see it really burdening the server too much unless you are operating at a very large scale. – jklina Apr 12 '16 at 15:59