Search code examples
ruby-on-railsformsosx-lionrubymine

form_tag action not working in rails


I have this form in my application.html.erb.

<%= form_tag(:action=>"index", :controller=>"posts") %>
  <p>
  // code here
  </p>

I dont understand why is this getting directed to posts->create instead of posts->index?

Thanks.


Solution

  • Basically, Rails observes and obeys "RESTful" web service architecture. With REST and Rails, there are seven different ways to interact with a server regarding a resource. With your current code, specifying the form's action as index doesn't make sense: Rails' form helpers can either POST, PUT or DELETE.

    If you wanted to create a post, then redirect to the index, you can do so in the applicable controller action:

    class PostsController < ApplicationController
    ...
    
    def create
      @post = Post.new
    
      respond_to do |format|
      if @post.save
        format.html { redirect_to(:action => 'index') }
    end
    end
    

    While your form would look like:

    <% form_for @post do |f| %>
      # put whatever fields necessary to create the post here
    <% end %>