Rails - 最佳方式/如何创建基于日期的导航
我是 Rails 新手,正在努力扩展我的基本博客应用程序的功能。我想做的是创建基于日期的导航链接。例如,我想要一个包含月份名称(作为链接)的链接列表,当您单击月份时,它会显示该月发布的所有文章。
我正在努力思考如何最好地实现这一目标。
我应该为 ArticleArchive 之类的东西创建一个新的模型/视图/控制器吗?或者根据我的需求,解决方案更简单?
我搜索了社区中的其他帖子,似乎没有人回答这个问题。任何有关如何构建和可能实现的帮助都将受到赞赏。谢谢!
I'm new to rails and am working on extending the functionality of my basic blog app. What I would like to do is create date-based navigation links. For example, I would like to have a list of links with the names of the months (as the links) and when you click on the month it shows you all the articles published in that month.
I'm struggling with how to best accomplish this.
Should I create a new Model / View / Controller for something like an ArticleArchive? Or is the solution more simple based on my needs?
I've searched the other posts in the community and none seemed to answer this. Any help with how to structure this and possibly implement is appreciated. Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是一个解决此问题的示例,尽管我想按天对其进行排序。这是针对您的控制器操作的:
要将其修改为月份,您需要执行类似于上面示例中的
r.published_at.beginning_of_month
的操作,本质上是group_by
的名称这个月。在视图模板中:
还有一个对此的截屏视频。
更新
好的 - 所以您只想显示月份的名称。将我们在索引操作中设置的实例变量与其他代码一起保存(您可能已经设置了
@articles = Article.all
)。然后在您想要列出链接的位置执行以下操作:Here's an example on approaching this, although in this I wanted to sort it by day. This is for your controller action:
To modify this to months, you'd want to do something like
r.published_at.beginning_of_month
in the example above and essentiallygroup_by
the name of the month.In the view template:
There's a screencast on this as well.
UPDATE
OK - so you only want the names of the month appearing. Keep the instance variable we setup in your index action along with your other code (you probably have setup
@articles = Article.all
). Then where you want the links listed do: