This question already has answers here:
Rails ActiveRecord date between
(11 answers)
Closed 9 years ago.
I'm trying to figure the best way to query a date range from rails...I looked around on Google but am unsure about how to use this syntax.
I have a Model that has various events and I like to add to my find condition a caveat that should only show events where the field :st_date is today or later, in effect only show me data that is current, nothing that happened before today.
I ran into a problem because I have no end date to stop the query, I want to query everything from today to next month.
I was thinking something like
#events = Event.find(:all, :conditions => ["start_date between ? and ?",
date.Today, date.next_month.beginning_of_month])
but I get the error undefined local variable or method `date'......
Do I need do anything particular to use the Date class? Or is there something wrong with my query syntax? I would really appreciate any help.
You want Date.today, not date.today. There's nothing wrong with what you're doing, you're just not referencing the date class properly
Furthermore it would be Date.today.next_month.beginning_of_month
I would take it a step further and define a scope in your model for reuse.
# rails 3 example:
# app/models/event.rb
scope :upcoming, lambda {
where("start_date between ? and ?", Date.today, Date.today.next_month.beginning_of_month)
}
# app/controllers/some_controller.rb
#events = Event.upcoming
There is also a great Railscasts episode on scopes in Rails 3:
http://railscasts.com/episodes/202-active-record-queries-in-rails-3
Event.where(:start_date => Date.today..Date.today.next_month.beginning_of_month) also works great.
Take a look at my by_star plugin which lets you do things like:
Event.by_month(Time.now, :field => "start_date")
Related
I try to delete from database all row has a id include in some array or (key,value)
"recp" => "1, 2, 3 , 6, 7 , ........."
ID in #recipient
I try this:
#v = NameOfDatabase.where.not(:id=> #recipient.split(',').map(&:to_i), :conditions => {:thread =>#dis_PI.m_id}).destroy_all
With specific condition i want to remove row with this condition and not include in #recipient
Error in this method :
NoMethodError (undefined method `where' for #<Class:0x7f447f57b140>):
I try multiple code but not working, i put this question multiple time but also not work yet!
From the comments, I learned that you are running a very old version of Ruby on Rails – probably more than 10 years old. With Rails 3.0 the finder methods change completely and therefore all current documentation for Rails will not be helpful anymore. Especially the where method did not exist before Rails 3.0
In such an old version the following should work:
YourModel.destroy_all("id in (?)", #recipient.split(','))
Here you will find the docs of older Rails versions.
The condition is basically just one SQL fragment. When you want to add more conditions then you need to write all conditions in one line like this:
YourModel.destroy_all(
"id IN (?) AND thread = ?", #recipient.split(','), #dis_PI.m_id
)
I can get easily find posts that have been commented on in the last 6 hours. However, I don't know how to order those posts by the number of comments made in the last 6 hours.
This is all I have:
Post.includes(:comments).where(comments: {created_at: 6.hours.ago...Time.now})
How do I order it? If the best way is to use a SQL query, I'm using PostgreSQL if it makes any difference.
I believe you want something like this:
Post.joins(:comments).where('comments.created_at BETWEEN ? AND ?', 6.hours.ago, Time.now).group('posts.id').order('COUNT(comments.id)')
If your requirement is different then feel free to comment and I will try to modify the answer.
I think it would be easiest for you to create a helper method for your Post model which returns the comments count:
def comments_count
comments.count
end
You can now do:
Post.includes(:comments).where(created_at: 6.hours.ago...Time.now).order(:comments_count)
It might be possible to do it without the helper method, I'm not sure but if you wanted to try:
Post.includes(:comments).where(created_at: 6.hours.ago...Time.now).order(:comments.count)
Hi I'm working on a project, and as part of it I want to be able to get all posts created within the last 7 days. I've tried:
#weeks_posts = Post.where(date: Date.today)
for i in 1..6
#weeks_posts = #weeks_posts + Post.where(date: (Date.today).to_time - i.days)
end
However this ends up returning an array which means I can't chain .where clauses to it, which I need to do, it also seems quite inefficient.
Any help would be greatly appreciated.
You can use scope to make it flexible:
scope :by_dates, ->(start_date, end_date) { Post.where(date: start_date..end_date) }
Post.by_dates(Date.today - 6.days, Date.today) # returns AR collection
Try something like this:
Post.where(date: 1.week.ago.beginning_of_day..Time.now)
Our app has a lease_booking model with a field of lease_date which is a datatime (we use sqlite for development and mysql for production). The app needs to find all the lease_booking on a given date. The code is like:
LeaseBooking.where("lease_date == ?", '2012-1-5')
The problem is that we can not find any lease_booking on 2012/1/5 because the lease_date is a date+time format. How can the app compare the date part only for a datatime field in rails 3.1?
thanks.
I'm afraid you'd have to do :
LeaseBooking.where("date(lease_date) = ?", '2012-1-5')
(with only one = sign)
Maybe there is a better answer, because call the "date" function is not really pretty for ActiveRecord! Like Jason Lewis says in the comments, it is DB-specific.
Alternately, try this:
scope :booking_date, lamda {|d| where('lease_date > ?', Date.parse(d).to_time).where('lease_date < ?', (Date.parse(d) +1).to_time)}
And just call
LeaseBooking.booking_date('2012-01-05')
The where-chaining is ugly, but whether or not you can use multiple ? placeholders, or named variables, to do it in one statement, is highly DB-dependent. ARel is pretty good at turning even ugly chained queries into efficient SQL, though.
HI
i would like to write a method that returns all the events that are on tomorrow or within the next 24 hours.
e.g
def tomorrows_events
#events = Event.will_occur_in next_24_hours
end
i have a datetime for each event which is called so to get it it would be, #event.date_and_time
i have the search logic gem installed but don't know if it supports dates, i couldn't find anything on it.
what would be the best way to write it? is there something in search logic i can use?
thanks
Event.all(:conditions => { :date_and_time => (Time.now.tomorrow.beginning_of_day)..Time.now.tomorrow.end_of_day})
I wrote a plugin that'll help you do this: http://github.com/radar/by_star.
You'd use this command for it:
Event.tomorrow(Time.zone.now, :field => "date_and_time")
Then it will return only results for tomorrow.