私は複雑なネストされたフォームを管理するために次のフォームオブジェクトを持っています。フォームオブジェクトを使用すると、編集アクションと更新アクションはどのように処理する必要がありますか?
フォーム
= 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オブジェクトを作成します。
さて、ありがとう、ありがとう。しかし、どのように、フォームのURLを変更する: '' = simple_form_for(@profile_form、:URL => profiles_path)やる| F | ''そして、私はエラーが表示さ:#のための ''未定義のローカル変数やメソッド 'IDを」 '' –
tomekfranek
@personがnilの場合はどうなりますか? – tomekfranek
'' to_param''メソッドを追加した後も同じエラーが表示されます。問題はURLであるように見えます。 – tomekfranek