当我使用表单对象时,我应该如何处理编辑和更新操作?

tom*_*nek 7 ruby forms ruby-on-rails object ruby-on-rails-3

我有跟随表单对象来管理复杂的嵌套表单.

形成

= simple_form_for(@profile_form, :url => profiles_path) do |f|
  ...
Run Code Online (Sandbox Code Playgroud)

路线

resources :profiles
Run Code Online (Sandbox Code Playgroud)

调节器

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
Run Code Online (Sandbox Code Playgroud)

表格对象

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
Run Code Online (Sandbox Code Playgroud)

但是现在当我使用这个表单create操作编辑对象时,会调用它.那么我应该如何重构这个表格呢?下面的代码update创建另一个Profile对象.

tor*_*o2k 6

simple_form_forform_for内部使用来完成它的工作.form_for使用该方法persisted?来确定对象是否已经持久存储在数据库中.如果已经持久化form_for将生成一个带有方法PUT的表单来更新对象,否则它将生成一个带有方法POST的表单来创建新对象.因此,您必须persisted?为表单对象实现该方法.你可以像这样实现它:

class ProfileForm
  # ...
  def persisted?
    @person.persisted? && @profile.persisted?
  end
  # ...
end
Run Code Online (Sandbox Code Playgroud)

更新在这种情况下@personnil,即没有Person到相关的Profile,我想你会创建一个新的Person关联到@profile.在这种情况下,它是安全的假设ProfileFormpersisted?,只要至少@profilepersisted?,这样的:

class ProfileForm
  # ...
  def persisted?
    @profile.persisted?
  end
  # ...
end
Run Code Online (Sandbox Code Playgroud)

更新为避免错误,undefined local variable or method `id'您必须为其定义id方法ProfileForm,如下所示:

class ProfileForm
  # ...
  def id
    @profile.id
  end
  # ...
end
Run Code Online (Sandbox Code Playgroud)