我对rails很陌生,所以如果我问这样一个基本问题,请原谅。
我的 html.erb 页面上有这个表格:
<%= form_tag(posts_path(:controller => "posts", :action => "create_thread"), :method => "post") do%>
Title:
<br></br>
<%= text_area_tag 'title', 'Thread\'s title is required!', :rows => 1, :cols => 30 %>
<br></br>
Message:
<br></br>
<%= text_area_tag 'body', nil, :rows => 15, :cols => 50 %>
<br></br>
<%= submit_tag "Create Thread" %>
<% end %>
我在控制器中定义了“create_thread”方法:
class PostsController < ApplicationController
def create_thread
logger.info("Thread created: ")
end
end
在 routes.rb 文件中,我为提交创建了一个路由:
resources :posts do
collection do
post 'index', :as => :create_thread
end
基本上,当我单击表单上的“创建线程”按钮时,我希望 Rails 执行 PostsController 类中的函数“create_thread”,然后加载“索引”页面。
然而,当我点击“创建线程”按钮时,它直接将我带到了“索引”页面(所以路径至少是有效的),但它没有在控制器中执行“create_thread”函数。
这是我单击按钮时在控制台上显示的内容:
Started POST "/posts?action=create_thread" for 127.0.0.1 at 2013-07-14 22:08:35 -0700
Processing by PostsController#index as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"9XVUrStaysmdOc6ug/A3XXX/8bzLkY8ixCkiAfHs9fU=", "title"=>"Thread's title is required!", "body"=>"", "commit"=>"Create Thread"}
这是 rake 路由的输出
root / posts#index
new_thread_posts GET /posts/new_thread(.:format) posts#new_thread
create_thread_posts POST /posts(.:format) posts#index
current_thread_post GET /posts/:id/current_thread(.:format) posts#current_thread
posts GET /posts(.:format) posts#index
POST /posts(.:format) posts#create
new_post GET /posts/new(.:format) posts#new
edit_post GET /posts/:id/edit(.:format) posts#edit
post GET /posts/:id(.:format) posts#show
PUT /posts/:id(.:format) posts#update
DELETE /posts/:id(.:format) posts#destroy
那么,如何让 Rails 执行 PostsController 中的“create_thread”函数?在过去的两天里,我一直在网上搜索,并尝试了各种各样的东西,但没有一个对我有用。
任何提示或指针将不胜感激!
预先感谢您的帮助。