ここには、リファクタリングに役立つコードがあります。Rails のフォームにリレーショナル データを追加するには、さまざまな方法が必要です。コードはhttp://railscasts.com/episodes/75-complex-forms-part-3から取得されます。私の問題は、Material モデルと Answer モデルの両方のメソッドが必要なことです。したがって、「材料」を「回答」に置き換えたまったく同じコードが2回必要です。
これは、動的プログラミングで解決する必要があるようです。しかし、私はそれについてまったく経験がありません。
これはどのように解決されますか?
after_update :save_materials
after_update :save_answers
def new_material_attributes=(material_attributes)
material_attributes.each do |attributes|
materials.build(attributes)
end
end
def existing_material_attributes=(material_attributes)
materials.reject(&:new_record?).each do |material|
attributes = material_attributes[material.id.to_s]
if attributes
material.attributes = attributes
else
materials.delete(material)
end
end
end
def save_materials
materials.each do |material|
material.save(false)
end
end