Marking multi-level nested forms as “dirty” in Rails

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-05 09:34:41

This is bug #4242 in Rails 2.3.5 and it has been fixed in Rails 2.3.8.

i think your models are wrong. the notes have no direct relationship to project. they are through milestones.

try these

class Project < ActiveRecord::Base
  has_many :milestones, :dependent => :destroy
  has_many :notes, :through => :milestones
  accepts_nested_attr ibutes_for :milestones, :allow_destroy => true
end

class Milestone < ActiveRecord::Base
  belongs_to :project
  has_many :notes, :dependent => :destroy

  accepts_nested_attributes_for :notes, :allow_destroy => true, :reject_if => proc { |attributes| attributes['content'].blank? }
end

class Note < ActiveRecord::Base
  belongs_to :milestone
end

Update: here is the code that worked for me based on the new info:

## project controller

# PUT /projects/1
def update
  @project = Project.find(params[:id])

  if @project.update_attributes(params[:project])
    redirect_to(@project)
  else
    render :action => "edit"
  end
end

# GET /projects/1/edit
def edit
  @project = Project.find(params[:id])
  @project.milestones.build
  for m in @project.milestones
    m.notes.build
  end
  @project.notes.build
end

## edit.html.erb
<% form_for(@project) do |f| %>
  <%= f.error_messages %>

  <p>
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </p>
  <% f.fields_for :notes do |n| %>
      <p>
        <div>
          <%= n.label :content, 'Project Notes:' %>
          <%= n.text_area :content, :rows => 3 %>
        </div>
      </p>
  <% end %>
  <% f.fields_for :milestones do |m| %>
      <p>
        <div>
          <%= m.label :name, 'Milestone:' %>
          <%= m.text_field :name %>
        </div>
      </p>
      <% m.fields_for :notes do |n| %>
          <p>
            <div>
              <%= n.label :content, 'Milestone Notes:' %>
              <%= n.text_area :content, :rows => 3 %>
            </div>
          </p>
      <% end %>
  <% end %>
  <p>
    <%= f.submit 'Update' %>
  </p>
<% end %>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!