实际上,Presenter 模式不一定最适合这里。
只需使用以下命令,您可能会更进一步accepts_nested_attributes_for
:
# Models
class Job < ActiveRecord::Base
has_many :tasks, :autosave => true
accepts_nested_attributes_for :tasks
end
class Task < ActiveRecord::Base
belongs_to :job
has_many :notes, :autosave => true
accepts_nested_attributes_for :notes
end
class Note < ActiveRecord::Base
belongs_to :task
end
然后在您的表单中执行类似(在 HAML 中)的操作:
= form_for @job do |job|
= job.text_field :name # or whatever your Job attributes are
= job.fields_for :tasks do |task|
= task.text_field :name
= task.check_box_field :complete
= task.fields_for :notes do |note|
= note.text_field :body
= job.submit "Create Job"
您可能必须为新工作实际初始化一些任务/注释,否则相关的记录表格可能不会显示。例如,3.times { @job.tasks.build }
创建 3 个空白任务(因此显示任务子表单 3 次)。