向现有控制器添加操作(Ruby on Rails) [英] Adding an action to an existing controller (Ruby on Rails)
问题描述
我是 Ruby on Rails 的新手,我已经完成了博客教程.
I am new to Ruby on Rails, I have completed the Blog Tutorial.
我现在正在尝试向控制器添加一个名为开始"的附加操作.
I am now trying to add an additional action to the controller, called 'start'.
def start
end
我添加了一个视图页面app/views/posts/start.html.erb",只包含简单的 html.
I have added a view page "app/views/posts/start.html.erb" containing nothing but simple html.
当我转到/posts/start 时,出现以下错误.
When I go to /posts/start i get the following error.
ActiveRecord::RecordNotFound in PostsController#show
Couldn't find Post with ID=start
我了解错误,正在执行 show 操作并且 start 不是有效 ID.为什么启动操作没有被执行,我是否缺少 MVC 架构或配置的某些部分?
I understand the error, the show action is being executed and start is not a valid ID. Why doesn't the start action get executed, is there some part of the MVC architecture or configuration I am missing ?
下面是我的posts_controller.rb
Below is my posts_controller.rb
class PostsController < ApplicationController
# GET /posts/start
def start
end
# GET /posts
# GET /posts.xml
def index
@posts = Post.find(:all)
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @posts }
end
end
# GET /posts/1
# GET /posts/1.xml
def show
@post = Post.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @post }
end
end
end
是的,我已经重新启动了服务器并尝试使用 Mongrel 和 webrick.
Yes I have restarted the server and tried it with Mongrel and webrick.
推荐答案
您的路由未设置为允许该路由.假设您使用的是默认脚手架,请将这一行放在 config/routes.rb 中的 map.resources :posts
行之前:
Your routing isn't set up to allow that route. Assuming you're using the default scaffolding, put this line before the map.resources :posts
line in config/routes.rb:
map.connect "posts/:action", :controller => 'posts', :action => /[a-z]+/i
:action
的正则表达式将其限制为 a-z(以避免捕获诸如/posts/1 之类的内容).如果您在新操作中需要下划线或数字,则可以对其进行改进.
The regex for :action
restricts it to just a-z (to avoid catching things like /posts/1). It can be improved if you need underscores or numbers in your new actions.
这篇关于向现有控制器添加操作(Ruby on Rails)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!