Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • form_for method in rails

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 147
    Comment on it

    Both form_for and form-tag are Rails helper methods. Whenever we want to build a form containing various elements like text-fields,text-areas,labels etc, we simply need a form builder object.

    form_for rails helper method just do that, it provides a form builder object to help creating a form.

    A typical example is given below;

    <%= form_for @event , url: user_events_path(current_user.id) do |f| %>
    <p>
    	<%= f.label :description %><br>
    	<%= f.text_area :description %>
    </p>
    <p>
    	<%= f.label :venue %><br>
    	<%= f.text_field :venue %>
    </p>
    <p>
    	<%= f.label :date %><br>
    	<%= f.date_field :date %>
    </p>
    
    <%= f.submit %>

    here, first argument it receives is an object of a model class. Second argument is a hash having key name url and value as a named route. The  block variable f is just that form builder object I was talking about, it simply creates three labels and their corresponding value holders.

    When we submit the form it gets submitted to the given action. The params hash now will have a key named event and it's value will be an another hash having description,venue and date as key names and their corresponding values as their values.

    The config/routes file is having a nested resource

     resources :users do
        resources :events 
        
      end

    and rake routes gives us

      user_events GET    /users/:user_id/events(.:format)   events#index
                  POST   /users/:user_id/events(.:format)   events#create
    new_user_event GET    /users/:user_id/events/new(.:format)     events#new
    edit_user_event GET    /users/:user_id/events/:id/edit(.:format) events#edit
        user_event GET    /users/:user_id/events/:id(.:format)       events#show
                   PATCH  /users/:user_id/events/:id(.:format)       events#update
                   PUT    /users/:user_id/events/:id(.:format)       events#update
                   DELETE /users/:user_id/events/:id(.:format)       events#destroy
    

    thanks.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: