Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does form_for decide what action is to be taken for a particular request?

I wrote the following code:-

<%= form_for(:session,url: login_path) do |f| %>

which got translated to

<form action="/login" accept-charset="UTF-8" method="post">  

my routes.rb file contains the following code:-

root 'static_pages#home' 
get 'contact'=>'static_pages#contact' 
get 'about'=>'static_pages#about'
get 'help' => 'static_pages#help'
get 'signup' => 'users#new'
get 'login' => 'sessions#new'
post 'login' => 'session#create'
delete 'logout' => 'session#destroy'
resources:users   

I want to know how the action of form_for is being decided?

like image 498
Aman Khare Avatar asked Dec 01 '25 09:12

Aman Khare


1 Answers

Here, where you don't specify instance object (@model_name), it just assigns form path to path you provide: login_path, method which just outputs "/login".

There are two routes

get 'login' => 'sessions#new'
post 'login' => 'session#create'

But as form_for default HTTP verb would be post, Rails matches incoming post request with 'login' => 'session#create'.

Method login_path is auto defined as you provide string 'login', unless you specify something other like post 'login' => 'session#create', as: "sign_in", which would do sing_in_path.

It is part of Rails backwards meta programming.

like image 168
Joe Half Face Avatar answered Dec 04 '25 00:12

Joe Half Face



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!