【发布时间】: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