【发布时间】:2013-06-12 11:19:58
【问题描述】:
我有以下表单对象来管理复杂的嵌套表单。
表格
= 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 对象。
【问题讨论】:
标签: ruby-on-rails ruby ruby-on-rails-3 forms object