Rails:自定义操作的 model_url
假设我有简单的 Rails 博客应用程序。
我有一个自定义操作,例如 page_views
,它显示帖子的浏览次数。
class PostsController < ApplicationController
def page_views
#show some page views
end
end
app/views/Posts
文件夹中还有一个关联的视图。
现在,在 routes.rb
中,我有:
map.resources :posts
map.resources :posts, :collection => {
:page_views=> :get
}
指向 page_views
视图的链接:
link_to("View Page Views",page_views_posts_path + "/" + post.id.to_s)
在我的帖子 show.html.erb
文件中,我有一个 paths
:
page_views_posts_path(post)
page_views_path(post)
page_views_posts(post)
要么导致找不到方法,要么导致网址不正确,例如:
http://localhost:3000/posts/page_views.#<posts:0xabcdef00>
我假设网址应该是:
http://localhost:3000/posts/page_views/1
那么,我在这里缺少什么?
Let's say I have the simple rails blog app.
And I have a custom action, like page_views
which shows the number of views of the post.
class PostsController < ApplicationController
def page_views
#show some page views
end
end
And there is also an associated view in the app/views/Posts
folder.
Now, in the routes.rb
I have:
map.resources :posts
map.resources :posts, :collection => {
:page_views=> :get
}
in my posts show.html.erb
file I have a link to the page_views
view:
link_to("View Page Views",page_views_posts_path + "/" + post.id.to_s)
Another paths
:
page_views_posts_path(post)
page_views_path(post)
page_views_posts(post)
Have either resulted in method not found or an incorrect url, like:
http://localhost:3000/posts/page_views.#<posts:0xabcdef00>
I would assume the url should be:
http://localhost:3000/posts/page_views/1
So, what I am missing here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您想为每个视图提供
page_views
页面,您应该声明额外的操作,而不是作为集合方法,而是作为成员方法:此外,如果您也希望所有帖子都这样做(显示某种排序表) )添加与收集操作相同的参数:
这样您将生成以下路由:
您可以通过运行以下命令来检查新路由:
考虑到您尚未为其他控制器声明它们,您将仅获得那些关联的视图。
If you want to provide
page_views
page for each view you should declare extra action not as collection method but as a member method:Also if you want this for all posts as well (show the ranking table of some sorts) add the same parameter as collection action:
This way you'll have following routes generated:
You can check new routes by running following command:
You will get only those associated views considering the fact that you haven't declared them for other controllers.
您还可以向
routes.rb
中的资源添加自定义方法,如下所示:并使用
page_views_posts_path
访问自定义方法。You can also add custom methods to resources in
routes.rb
like this:And use
page_views_posts_path
to access to the custom method.