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

拈花ヽ惹草 提交于 2019-11-28 17:57:00
Dipak Panchal

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

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 %>

URL:

Url is the path where your form data should go. whatever you write inside the :url symbol is considered as the path where your data should go when u click a submit button in the form.

Action:

Action is the method in your controller, in your form_for @user (where @user is a object of User model), if you say :action => create then it sumbit the data to users_controller 'create' function (def create). You will mention this inside :url to tell that the data should go to the specifiled action.

Method:

Is http method, there are 'get', 'post', 'update', 'patch' and 'delete' method. You can learn about this in google.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!