ruby-on-rails – Ruby on rails从视图路由到控制器中的自定义方法

我有一个控制器名称帖子.在我的/config/routes.rb中,我使用了这个 –
resources :posts

/app/controllers/posts_controller.rb:

class PostsController < ApplicationController
    def new
            @post = Post.new
    end

    def show
            @post = Post.find(params[:id])
    end

    def categoryshow
            @post = Post.find(params[:category])
    end

    def index
            @posts = Post.all
    end

    def create
            @post = Post.new(params[:post])
            if @post.save
                    flash.Now[:success] = "Your Post Successful"
                    redirect_to @post
            else
                    render 'new'
            end
    end
end

我是新手,我经常对路线感到困惑.我有一个static_pages控制器.在home.html.erb文件中.

我想做的是致电 –

def categoryshow
            @post = Post.find(params[:category])
end

来自/app/views/static_pages/home.html.erb的帖子控制器的’categoryshow’方法

我该如何管理?如果我使用’posts_path’,它将转到索引操作而不是categoryshow操作.

#

我通读了这个链接并尝试了一些东西.这是我面临的问题:

当我在config / routes.rb中尝试这个时

resources :posts do

    collection do

          get 'categoryshow'

    end

end

这会生成’categoryshow_posts_path’

在我看来,我使用了这个:

<ul class="users">

     <%= Post::CATEGORIES.each do |category| %>

<li>

     <%= link_to category,categoryshow_posts_path %>

</li>

<% end %>

</ul>

我的帖子控制器有以下方法

def categoryshow

@post = Post.find(params[:category])

结束

在这种情况下,我收到以下错误

PostsController #categyshow中的ActiveRecord :: RecordNotFound

无法找到没有ID的帖子

其次,我尝试使用您提供的链接中提到的非资源路由:

match ':posts(/:categoryshow(/:category))'

在视图中,我使用这个:

分类

<ul class="users">

 <%= Post::CATEGORIES.each do |category| %>

 <li>

     <%= link_to category,"posts/#{category}" %>

 </li> 

<% end %>

</ul>

在这种情况下,只有当没有其他现有的资源路由匹配时,我们的非资源路由才会匹配.但是,我看到显示操作匹配,我收到此错误消息:

这是show动作:

def show

@post = Post.find(params[:id])

结束

PostsController#show中的ActiveRecord :: RecordNotFound

找不到具有id = Politics的帖子

>我真的很感激这里的任何帮助!!
>谢谢(Sidharth)

解决方法

查看 “Adding More RESTful Actions” sections of the routing docs.
resources :posts do
collection do
get 'categoryshow'
end
end

要么:

resources :posts do
  get 'categoryshow',:on => :collection
end

之后的部分讨论了如果不满足您的确切需求则添加任意路由.

请注意,路由文件是明确排序的:如果您尝试在其他东西捕获后匹配路由,则第一条路线获胜.

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...