0

I have the following two form_for() that I am confused about.

# form for users
form_for(@user) do |f|

# form for sessions
form_for(:sessions, url: login_path) do |f|

I understand that the first one is simply go through all the users and input the form. I am not sure why when you create a new session, the parameters for form_for is listed as such. Why is there a login path?

Michael Hartl explained it as "in the case of sessions we need to indicate the name of the resource and the corresponding URL", but that doesnt' really explain anything to me.

any enlightenment would be nice!

2 Answers 2

2

Passing :url to form_for method is optional when dealing with a model object. when using it to create a new object:

# long-style:
form_for(@user, url: users_path)
# same thing, short-style (record identification gets used)
form_for(@user)

In the short-style version a concept called Record Indentification is used, basically rails figures out if the record is new by asking record.new_record? It also selects the correct path to submit to based on the class of the object, in this case @user.class

Same principle applies when using form_for when updating an existing object. In this case the record.new_record? returns false, and rails figures out it must submit the form to the update action of the controller.

In cases when the path that the form must submit to cannot be figured out by rails using the above mechanism, then the url must be provided explicitly. This also applies when defining Singular Resources such as resource :geocoder. when creating forms for singular routes, the URL must be specified:

form_for @geocoder, url: geocoder_path do |f| 
Sign up to request clarification or add additional context in comments.

Comments

0

In the first case, the form_for helper inspects the @user variable to see its state. The User might be a new record (in which case the form points to /users with POST*) or an existing record (users/:id with PATCH). It can also provide pre-filled inputs based on the variable's state.

The second form is used when there's no need for an instance of a model (or maybe the model doesn't even exists) and the form_for helper is used just for convenience. The url parameter is explicitly set because by default the action would point to the current URL and you want it to point to login_path.

*Technically they are both POST on the browser side, Rails will distinguish between them later.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.