I have the following form object to manage a complex nested form.
The form
= simple_form_for(@profile_form, :url => profiles_path) do |f| ...
Routes
resources :profiles
controller
class ProfilesController < ApplicationController def new @profile_form = ProfileForm.new end def edit @profile_form = ProfileForm.new(params[:id]) end def create @profile_form = ProfileForm.new if @profile_form.submit(params[:profile_form]) redirect_to @profile_form.profile, notice: 'Profile was successfully created.' else render action: "new" end end def update @profile_form = ProfileForm.new(params[:id]) if @profile_form.submit(params[:profile_form]) redirect_to @profile_form.profile, notice: 'Profile was successfully updated.' else render action: "edit" end end end
Form object
class ProfileForm include ActiveModel::Validations include ActiveModel::Conversion extend ActiveModel::Naming def initialize(profile_id = nil) if profile_id @profile = Profile.find(profile_id) @person = profile.person end end ... def submit(params) profile.attributes = params.slice(:available_at) person.attributes = params.slice(:first_name, :last_name) if valid? profile.save! person.save! true else false end end def self.model_name ActiveModel::Name.new(self, nil, "Profile") end def persisted? false end end
But right now, when I edit an object using this create form, an action is called. How should I reorganize this form? The code below on update creates another Profile object.
tomekfranek
source share