如何在 Rails 中按日期范围进行搜索?
我编写了一个 Rails 控制器函数,用于查询 MySQL 数据库,查找在特定日期范围内添加的条目。例如,类似于以下内容:
@foos = FooTableModel.where(created > ? AND created <= ?', DateTime.new(2011, 1, 26), DateTime.new(2011, 1, 29))
此查询非常适合我的目的。然而,我想做的是允许用户设置他们想要的日期范围,而不是明确设置它。我对 erb 文件进行了一些研究,并且在访问数据方面取得了巨大成功,我只对更改我要求显示的数据感兴趣。
有没有与我想要实现的目标类似的示例?我认为这是 Rails 开发人员希望让他们的用户能够做的一件相当普遍的事情,但我在线索方面运气不佳。
I've written a Rails controller function that queries a MySQL database looking for entries that were added within a certain date range. Something like the following, for instance:
@foos = FooTableModel.where(created > ? AND created <= ?', DateTime.new(2011, 1, 26), DateTime.new(2011, 1, 29))
This query works great for my purposes. What I would like to do, however, is to allow the user to set their desired date range rather than have it explicitly set. I've poked around with erb files somewhat and I've had great success accessing the data, I'm exclusively interested in altering what data I call for to display.
Are there any examples that are similar to what I'm trying to achieve? I assume this is a fairly common thing Rails developers would like to enable their users to do but I haven't had much luck with leads.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你的表单代码在哪里?
这是一个标准的 REST 表单:
然后在您的控制器中,您可以使用参数按这些日期进行搜索。
请记住
foo_path
需要是静态路由。如果不是,那么您需要传递一个哈希{:controller =>; 'foo', :action =>; "find"}
在你的控制器中你可以执行如下操作:
Where is your form code?
Here is a standard REST form:
Then in your controller you can use the parameters to search by those dates.
Keep in mind
foo_path
needs to be restful route. If it is not then you need to pass a hash{:controller => 'foo', :action => "find"}
In your controller you can do something like this: