Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RoR differences between :url, :action, :method in form_for

Tags:

There might be answers in documentation, but i don't seem to find good answers. So among the three :url, :action, :method, what are their differences when used in form_for in Rails?

like image 535
sovanlandy Avatar asked Nov 27 '12 03:11

sovanlandy


2 Answers

Difference between :url, :action and :method

:url

If you want to submit your form for any particular controller, any particular action and want to pass some extra parameter (use action that define in controller that you pass on controller )

for example

<%= form_for @post, :url => {:controller => "your-controller-name", :action => "your-action-name"} do |f| %> 

In the above code the form is submitted to that controller(that you pass on url) and goto that (you pass on action) action. it will take defaults to the current action.

now suppose you want to pass extra parameter then for example

form_for @post, :url => { :action => :update, :type => @type, :this => @currently_editing } do |f| ... 

you can pass extra parameter like :type => @type

so :url is The URL the form is submitted to. It takes the same fields you pass to url_for or link_to. In particular you may pass here a named route directly as well.


:action

 form_for @post, :url => { :action => :update, :type => @type, :this => @currently_editing } do |f| ... 

In the above example we pass :action if we want to submit the form in different action then we pass :action and your-action-name the form is post to that action


:method

method is used for which method you want to pass for that action. There are several methods like put,post,get ...

for example

form_for @post, :url => post_path(@post), :method => :put, .... 

In the above form_for we pass :method => :put when this form is submit it will use put method

like image 190
Dipak Panchal Avatar answered Oct 24 '22 04:10

Dipak Panchal


form_for is basically used on object. For example:

      <% form_for @person do |f| %>        ...       <% end %> 

When you click submit it will go to default action like from :new to :create, :edit => :update. If you want to specify your own action then you have to use :url and :method is used to force to post or get. For example:

      <% form_for @person :url => {:action => "my_action"}, :method => "post" do |f| %>        ...       <% end %> 
like image 36
dealer Avatar answered Oct 24 '22 06:10

dealer