Mark
Mark

Reputation: 1983

passing a symbol/instance variable to form_for doesn't generate the intended action

I saw this answer and this both claim that the difference between passing a symbol into form_for, that is, <% form_for :post do |f| %> and
<% form_for @post do |f| %>

One difference is that action = /posts/create but I found something different, actually action=/posts instead of what was claimed.

When you pass a instance you get

<form class="new_form" id="new_form" action="/forms"

But when you pass a symbol you get

<form action="/forms"

(for both html versions I omitted charset and hidden etc)

So what's going on

Upvotes: 0

Views: 39

Answers (1)

max
max

Reputation: 101811

The difference between <% form_for :post do |f| %> and <% form_for @post do |f| %> is that the latter binds the form to a model instance.

The latter will actually "hold" the values the user types in after submission. form_for :post just uses polymorphic routing the get the route and nests the inputs under the key :post.

Both generate the action /posts (for a new record) unless you really messed up the routes. form_for @post will generate a route to /posts/:id and change the method to patch if the record is #persisted?.

These are the conventional routes created by resources:

GET          /posts               posts#index
GET          /posts/:id           posts#show
GET          /posts/new           posts#new
POST         /posts               posts#create
GET          /posts/:id/edit      posts#edit
PATCH|PUT    /posts/:id           posts#update
DELETE       /posts/:id           posts#destroy

/posts/create is not a conventional route and will never be generated unless you define the route manually.

Upvotes: 1

Related Questions