Rubytastic
Rubytastic

Reputation: 15501

split 1 big form into several sub forms

What would be the best way to split a user profile model and its form into several sub forms that you can update separately?

like * basic details

You can only have 1 edit action, so what would be the preferred way of handling this?

Upvotes: 1

Views: 235

Answers (2)

jklina
jklina

Reputation: 3417

If you're only updating you might just be able to use the standard edit/update action and just make smaller forms. Just create the forms as usual and simply include just the fields you want and have them all point to your normal update action.

If you're creating a new user from the smaller forms you might run into problems with validating different fields, but if you're just updating then the minium requirements for validation should already be met

Upvotes: 1

TheDelChop
TheDelChop

Reputation: 7998

So in reality, what you really probably want to do is create a set of nested resources for the user, so that you can treat each of these separately.

resources :users do
  resource :basic_details
  resource :detailed_details
  resources: :photos
  resources: interests
end

Which gives you routes like: edit_user_basic_details(@user), so then, you can have forms that hit the update actions of these sub resources, like this:

<%= form_for :basic_details, url: user_basic_details_path(@user) do |form| %>
  <%= form.text_field :name %>
  <%= form.submit %>
<%= end %>

This way, you can setup controllers like this:

class BasicDetailsController < ApplicationController
  def edit
   @user = User.find(params[:user_id])
  end

  def update
   @user = User.find(params[:user_id])
   @user.update_attribures(params[:basic_details])
  end
end

This is a very quick and dirty way to implement this, but its meant to show you have to get started. You don't have to think about form and controllers as only editing tables in your database, sometimes its much more convenient to think about particular parts of one of your models as its own resource which can be edit separately.

Hope this gets you started.

Upvotes: 1

Related Questions