【问题标题】:Ruby on rails route to a custom method in the controller from the viewRuby on rails 从视图路由到控制器中的自定义方法
【发布时间】:2012-06-26 01:19:30
【问题描述】:

我有一个控制器名称职位。在我的/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

我是 Rails 新手,经常对路线感到困惑。我有另一个 static_pages 控制器。里面有一个home.html.erb 文件。

我想做的就是打电话-

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

来自/app/views/static_pages/home.html.erb的posts控制器的'categoryshow'方法

我该如何管理?如果我使用“posts_path”,它会转到 index 操作而不是 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>

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

定义类别展示

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

结束

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

ActiveRecord::RecordNotFound in PostsController#categoryshow

找不到没有 ID 的帖子


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

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

在视图中,我正在使用这个:

类别

 <ul class="users">

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

 <li>

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

 </li> 

<% end %>

</ul>

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

这是表演动作:

默认显示

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

结束

ActiveRecord::RecordNotFound in PostsController#show

找不到 id=Politics 的帖子

  • 非常感谢这里的任何帮助!

  • 谢谢(Sidharth)

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    查看"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
    

    如果不能满足您的确切需求,那么后面的部分将讨论添加任意路由。

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

    【讨论】:

    • 请注意,如果方法需要参数,则为collection,否则为member。第二种方式看起来更好,因为只有一个新动作要添加。当有 2 个或更多动作时使用块。不是吗?
    • @KleberS。我对是否使用块感到矛盾;我发现第一个版本更容易推理,因为它是什么类型的路线一目了然。
    • 有什么帮助吗?我添加了我尝试过的任何内容,但仍然无法解决问题..
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-05
    • 1970-01-01
    • 1970-01-01
    • 2016-09-26
    • 1970-01-01
    相关资源
    最近更新 更多