用一些动态编程重构?

Fre*_*rik 0 ruby metaprogramming ruby-on-rails dynamic

我在这里有一段代码,我真的可以在重构时使用一些帮助.我需要在rails中以表格形式添加关系数据的不同方法.代码来自http://railscasts.com/episodes/75-complex-forms-part-3,我的问题是我需要有Material模型和Answer模型的方法.所以我需要完全相同的代码两次,"材料"替换为"答案".

这似乎应该通过一些动态编程来解决?但我对此毫无经验.

这是怎么解决的?

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

srb*_*ert 5

您可能还想看看这个网站:

http://refactormycode.com/