我的 application.html.erb 中有这个表格。
<%= form_tag(:action=>"index", :controller=>"posts") %>
<p>
// code here
</p>
我不明白为什么这会被定向到posts->create
而不是posts->index
?
谢谢。
我的 application.html.erb 中有这个表格。
<%= form_tag(:action=>"index", :controller=>"posts") %>
<p>
// code here
</p>
我不明白为什么这会被定向到posts->create
而不是posts->index
?
谢谢。
对于每个动作的用途,您似乎有些混淆。以下是典型 RESTful 用法的快速总结:
索引 -> 查看项目列表
新建/编辑 -> 添加或编辑项目的表单
创建/更新-> 创建/更新项目的控制器操作
您的路线文件未将您编入索引的原因是因为索引不是通常创建或更新帖子的操作。最好的方法是使用 RESTful。除非您遇到非常不寻常的情况,否则设置系统的最佳方法可能有点像这样:
# routes.rb
resources :posts
# application.html.erb (or better: posts/_form.html.erb).
<% form_for @post do |f| %>
<% end %>
# posts controller, whichever action you want to use
def new
@post = Post.new
end
通过将表单放入部分调用中,form
您可以在 、 或您需要在系统中操作帖子的任何其他位置访问new
它edit
。
基本上,Rails 遵守并遵循“ RESTful ”Web 服务架构。使用 REST 和 Rails,有七种不同的方式可以与服务器就资源进行交互。使用您当前的代码,将表单的操作指定为索引没有意义:Rails 的表单助手可以 POST、PUT 或 DELETE。
如果您想创建一个帖子,然后重定向到索引,您可以在适用的控制器操作中执行此操作:
class PostsController < ApplicationController
...
def create
@post = Post.new
respond_to do |format|
if @post.save
format.html { redirect_to(:action => 'index') }
end
end
虽然您的表格看起来像:
<% form_for @post do |f| %>
# put whatever fields necessary to create the post here
<% end %>