我有以下表单对象来管理复杂的嵌套表单。
形式
= simple_form_for(@profile_form, :url => profiles_path) do |f|
...
路线
resources :profiles
控制器
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
表单对象
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
但是现在,当我使用此表单create
操作编辑对象时,它会被调用。那么我应该如何重构这个表单呢?下面的代码update
创建另一个 Profile 对象。