randombits
randombits

Reputation: 48440

Rails form posting to /new instead of /create?

I have a simple form view using a Rails 3.1.x application:

<%= form_for(:mymodel) do |f| %>
  <% if @mymodel.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@mymodel.errors.count, "error") %> prohibited this model from being saved:</h2>

      <ul>
      <% @mymodel.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    Amount:
    <%= f.text_field :count %><br /><br />
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

When submit is hit here, it posts to /mymodels/new. How do I force it to go to the right create action for mymodels_controller.rb?

Upvotes: 4

Views: 2125

Answers (1)

F&#225;bio Batista
F&#225;bio Batista

Reputation: 25270

Option 1: Follow the conventions and supply a new, unsaved record to the form_for helper. You probably already have such object on @mymodel, set on your new action of your controller. So the following snippet should work nicely:

<%= form_for(@mymodel) do |f| %>

If it does not work, you can set @mymodel on your action like this:

class MyModelsController
  def new
    @mymodel = MyModel.new
  end
end

Option 2: Be explicit about your URL and method:

<%= form_for(:mymodel, :url => create_mymodel_path, :method => :post) do |f| %>

Upvotes: 6

Related Questions