0

I'm very new to rails, so please excuse me if I'm asking such a basic question.

I had this form on my html.erb page:

<%= 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 %>

I defined the "create_thread" method in the controller:

class PostsController < ApplicationController
    def create_thread
      logger.info("Thread created: ")
    end
end

In the routes.rb file, I created a route for the submit:

resources :posts do
collection do
  post 'index', :as => :create_thread
end

Basically, when I click on the "Create Thread" button on the form, I would like rails to execute the function "create_thread" in the PostsController class, and then load the "index" page.

However, when I clicked on the "Create Thread" button, it took me straight to the "index" page (so the path is working, at least), but it did not execute the "create_thread" function in the controller.

This was what it showed on the console when I clicked on the button:

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"}

Here's the output of rake routes

               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

So, how do I get rails to execute the "create_thread" function in PostsController? I have been searching over the web in the past 2 days, and trying all sorts of stuff, but none has worked for me.

Any hint or pointer would be greatly appreciated!

Thank you in advance for your help.

4

1 に答える 1

0

以下を試してください

resources :posts do
  post :create_thread, on: :collection
end

form_tag(controller: :posts, action: :create_thread)
于 2013-07-15T17:54:07.100 に答える