惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

The GitHub Blog
The GitHub Blog
博客园_首页
T
Threatpost
S
Secure Thoughts
月光博客
月光博客
S
Schneier on Security
爱范儿
爱范儿
C
CXSECURITY Database RSS Feed - CXSecurity.com
阮一峰的网络日志
阮一峰的网络日志
Microsoft Azure Blog
Microsoft Azure Blog
L
LINUX DO - 热门话题
C
Cyber Attacks, Cyber Crime and Cyber Security
大猫的无限游戏
大猫的无限游戏
Cyberwarzone
Cyberwarzone
Blog — PlanetScale
Blog — PlanetScale
A
About on SuperTechFans
F
Fortinet All Blogs
云风的 BLOG
云风的 BLOG
C
CERT Recently Published Vulnerability Notes
Project Zero
Project Zero
P
Proofpoint News Feed
B
Blog
Microsoft Security Blog
Microsoft Security Blog
L
LangChain Blog
G
GRAHAM CLULEY
S
Securelist
K
Kaspersky official blog
Spread Privacy
Spread Privacy
Stack Overflow Blog
Stack Overflow Blog
Security Latest
Security Latest
aimingoo的专栏
aimingoo的专栏
Cisco Talos Blog
Cisco Talos Blog
T
Tor Project blog
I
Intezer
NISL@THU
NISL@THU
The Register - Security
The Register - Security
P
Privacy International News Feed
Recent Announcements
Recent Announcements
MyScale Blog
MyScale Blog
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
T
Tenable Blog
AI
AI
V2EX - 技术
V2EX - 技术
量子位
Jina AI
Jina AI
博客园 - Franky
N
News | PayPal Newsroom
Cloudbric
Cloudbric
N
News and Events Feed by Topic
J
Java Code Geeks

Ruby on Rails: Compress the complexity of modern web apps

Safer to_i coercion, custom to_fs formats, and more! This Week in Rails: May 16, 2026 This Week in Rails: May 8, 2026 This Week in Rails: May 1, 2026 Active Record gets better every week Great big Rails World 2026 update: CFP, Corporate Support tickets, workshops Query command for database queries and more Explicit query: and body: kwargs for integration tests and more! Speedup ActiveRecord::LogSubscriber#sql_color and more! This Week in Rails: March 27, 2026 Rails Versions 8.0.5 and 8.1.3 have been released! Rails Versions 7.2.3.1, 8.0.4.1, and 8.1.2.1 have been released! This Week in Rails: March 20, 2026 Validate URI scheme in Action Text and more This Week in Rails: March 6, 2026 Planning Center is the newest Rails Foundation Contributing member Action Text gets Markdown conversion, editor links in devcontainers, and more! BARRA seeks Rails developer Joe Agliozzo is looking for a Rails developer The rise of lighttpd as the alternative web server When longer is better and more is more Snowdevil: First e-tailer on Rails Natural selection for frameworks in Ruby vs Java Address book tutorial in Portuguese Becoming a better programmer with Rails 10 Things Every Java Programmer Should Know About Ruby Really Getting Started in Rails Off the Treadmill, Onto the Rails Rails 0.9.5: A world of fixes and tweaks Rich clients with Rails and XUL Pedrosa on Rails vs WebWork: 'Language DOES matter' 'Ruby on Rails is unbelievably good' Celebrating six months anniversary! Speeding up CGI access to Gem Rails CD Baby leaves PHP behind for Ruby on Rails "I think Ruby on Rails is way over hyped" Programmer needed for JSP to Rails conversion Beyond the 10,000th gem install of Rails 'That application is so stupid' Matz takes note of Ta-da and Rails Rails tutorial on O'Reilly's ONLamp Welcome Slashdotters! Ta-da goes international with UTF-8 Make your Ta-da list today Rails 0.9.4.1: Cleaning up the mess Rails 0.9.4: Caching, filters, SQLite3... An unusual high presence of Macs Having problems running tests under 1.8.2? It\'s all about the applications But what does Rails go web services with XML-RPC prototype Rails runs through XP Cincinnati RedHanded out-evangelizes the evangelizer Rails on Lighttpd with FastCGI Have a codefest and collect cash from RubyCentral Jamis Buck is working on Basecamp S5 Presents competes with SoapBX 3,000 people are doing 10,804 things... Using the Rails to impress potential employers Brian discovers the default logging goodness SoapBX: Presentations powered by S5, Textile, Rails Road Map: The rails leading to 1.0 Tracks: A Getting Things Done implementation Nicholas presents the Directors Rails 0.9.3: Optimistic locking, dynamic finders, 1.8.2 Ruby on the German Rails 43things in 5,204 lines of Ruby on Rails Watch for huge requests on default FCGI How the redesign of the website came to be Are you watching the health of your software? "Some amazing web apps appear on Ruby on Rails" Learning Ruby on Rails with 43things The Robot Co-op takes 43things.com live! Giving up on Java for lack of love Setting up EliteJournal on TextDrive without a vhost Celebrating 219 applied patches since 0.7 Escaping Java but not its thinking "Simple design that even my grandma can understand" Rails logo remixed by Olivier Hericord Rake 0.4.14 includes fix for Ruby 1.8.2 Splitting off the research patches Running rake tests with Ruby 1.8.2 Marten opens Epilog for Trac'ing Drew McLellan predicts Rails celebrates more than 10,000 downloads Variations on a railed theme Securing your Rails: Keep it secret, keep it safe Available for hire? Collaboa and EliteJournal joins the Trac Playing Active Records on MS SQLServer and DB2 Open sourcing the Rails logo Rails: Technology of the Year #1 Reacting to customer requests in real time Extracting missing content from wiki backups Ruby on Rails has its web presence overhauled 43 things makes The Seattle Times 5.gets David Heinemeier Hansson Ruby 1.8.2 finally sees the light of day Rails 0.9: Fast development, breakpoints, validations Rails 0.9.1: Small, but important bugfix for Action Pack
Nested Model Forms
David Heinemeier Hansson · 2009-01-26 · via Ruby on Rails: Compress the complexity of modern web apps

The most popular request on our new Feedback site was for the ability to easily manage multiple models in a single form. Thankfully Eloy Duran has a patch that does just this. But before we roll it into rails 2.3 we want to get some more feedback from you guys. Eloy's written this brief introduction to the patch, so take a look, and add any feedback you have to the lighthouse ticket.

In Rails it has always been a little tricky to create a single form for both a model and its associations. Last summer, the :accessible option was committed as a first stab at a unified solution for dealing with nested models. However, this feature was pulled before the 2.2 release because it only supported nested models during object creation.

The resulting discussion on the core mailing list and our need for mass assignment have resulted in this patch for ticket #1202 which is now up for scrutinizing.

Since this is a rather large patch we would like to invite you to give it a try. Please report any issues or give feedback about the patch in general. We are especially interested to know how the provided solutions work for applications that allow deletion of nested records through their forms.

Below I'll give a quick tour on what the patch does and how to use it so you have no excuse not to give it a try.

Get the patch

Start by creating a new application:

$ mkdir -p nested-models/vendor
$ cd nested-models/vendor

Vendor your Rails branch with the nested models patches:

$ git clone git://github.com/alloy/rails.git
$ cd rails
$ git checkout origin/normalized_nested_attributes
$ cd ../..
$ ruby vendor/rails/railties/bin/rails .

An example of nested assignment

Suppose you have a project model with associated tasks:

class Project < ActiveRecord::Base
  has_many :tasks

  validates_presence_of :name
end
class Task < ActiveRecord::Base
  belongs_to :project

  validates_presence_of :name
end

Now consider the following form which allows you to simultaneously create (or edit) a project and its tasks:

<form>
  <div>
    <label for="project_name">Project:</label>
    <input type="text" name="project_name" />
  </div>

  <p>
    <label for="task_name_1">Task:</label>
    <input type="text" name="task_name_1" />
    <label for="task_delete_1">Remove:</label>
    <input type="checkbox" name="task_delete_1" />
  </p>

  <p>
    <label for="task_name_2">Task:</label>
    <input type="text" name="task_name_2" />
    <label for="task_delete_2">Remove:</label>
    <input type="checkbox" name="task_delete_2" />
  </p>
</form>

Before the patch

Before this patch you would have to write a template like this:

<% form_for @project do |project_form| %>
  <div>
    <%= project_form.label :name, 'Project name:' %>
    <%= project_form.text_field :name %>
  </div>

  <% @project.tasks.each do |task| %>
    <% new_or_existing = task.new_record? ? 'new' : 'existing' %> 
    <% prefix = "project[#{new_or_existing}_task_attributes][]" %> 
    <% fields_for prefix, task do |task_form| %>
      <p>
        <div>
          <%= task_form.label :name, 'Task:' %>
          <%= task_form.text_field :name %>
        </div>

        <% unless task.new_record? %>
          <div>
            <%= task_form.label :_delete, 'Remove:' %>
            <%= task_form.check_box :_delete %>
          </div>
        <% end %>
      </p>
    <% end %>
  <% end %>

  <%= project_form.submit %>
<% end %>

The controller is pretty much your average restful controller. The Project model however needs to know how to handle the nested attributes:

class Project < ActiveRecord::Base
  after_update :save_tasks

  def new_task_attributes=(task_attributes)
    task_attributes.each do |attributes|
      tasks.build(attributes)
    end 
  end

  def existing_task_attributes=(task_attributes)
    tasks.reject(&:new_record?).each do |task|
      attributes = task_attributes[task.id.to_s]
      if attributes['_delete'] == '1'
        tasks.delete(task)
      else
        task.attributes = attributes
      end
    end
  end

  private

  def save_tasks
    tasks.each do |task|
      task.save(false)
    end
  end

  validates_associated :tasks
end

The code above is based on Ryan Bates' complex-form-examples application and from the Advanced Rails Recipes book.

After this patch

First you tell the Project model to accept nested attributes for its tasks:

class Project < ActiveRecord::Base
  has_many :tasks

  accept_nested_attributes_for :tasks, :allow_destroy => true
end

Then you could write the following template:

<% form_for @project do |project_form| %>
  <div>
    <%= project_form.label :name, 'Project name:' %>
    <%= project_form.text_field :name %>
  </div>

  <!-- Here we call fields_for on the project_form builder instance.
       The block is called for each member of the tasks collection. -->
  <% project_form.fields_for :tasks do |task_form| %>
      <p>
        <div>
          <%= task_form.label :name, 'Task:' %>
          <%= task_form.text_field :name %>
        </div>

        <% unless task_form.object.new_record? %>
          <div>
            <%= task_form.label :_delete, 'Remove:' %>
            <%= task_form.check_box :_delete %>
          </div>
        <% end %>
      </p>
    <% end %>
  <% end %>

  <%= project_form.submit %>
<% end %>

As you can see this is much more concise and easier to read.

Granted, the template for this example is only slightly shorter, but it's easy to imagine the difference with more nested models. Or if the Task model had nested models of its own.

Validations

Validations simply work as you'd expect; #valid? will also validate nested models, #save(false) will save without validations, etc.

The only thing to note is that all error messages from the nested models are copied to the parent errors object for error_messages_for. This will probably change in the future, as discussed on the ticket, but that's outside of the scope of this patch.

Let's look at an example where Task validates the presence of its :name attribute:

>> project = Project.first
=> #<Project id: 1, name: "Nested models patches", created_at: "2009-01-22 11:17:15", updated_at: "2009-01-22 11:17:15", author_id: 1>

>> project.tasks
=> [#<Task id: 1, project_id: 1, name: "Write 'em", due_at: nil, created_at: "2009-01-22 11:17:15", updated_at: "2009-01-22 11:17:15">,
#<Task id: 2, project_id: 1, name: "Test 'em", due_at: nil, created_at: "2009-01-22 11:17:15", updated_at: "2009-01-22 11:17:15">,
#<Task id: 3, project_id: 1, name: "Create demo app", due_at: nil, created_at: "2009-01-22 11:17:15", updated_at: "2009-01-22 11:17:15">,
#<Task id: 4, project_id: 1, name: "Scrutinize", due_at: nil, created_at: "2009-01-22 11:17:15", updated_at: "2009-01-22 11:17:15">]

>> project.tasks.second.name = "" 
=> "" 

>> project.valid?
=> false

>> project.errors
=> #<ActiveRecord::Errors:0x23e4b10 @errors={"tasks_name"=>["can't be blank"]}, @base=#<Project id: 1, name: "Nested models patches", …, author_id: 1>>

Transactions

By now you are probably wondering about the consistency of your data when validations passes but saving does not. Consider this Author model which I have rigged to raise an exception after save:

class Author < ActiveRecord::Base
  has_many :projects

  after_save :raise_exception

  def raise_exception
    raise 'Oh noes!'
  end
end

Here's the Project data before an update:

>> project = Project.first
=> #<Project id: 1, name: "Nested models patches", created_at: "2009-01-22 11:17:15", updated_at: "2009-01-22 11:17:15", author_id: 1>

>> project.tasks
=> [#<Task id: 1, project_id: 1, name: "Write 'em", due_at: nil, created_at: "2009-01-22 11:17:15", updated_at: "2009-01-22 11:17:15">,
#<Task id: 2, project_id: 1, name: "Test 'em", due_at: nil, created_at: "2009-01-22 11:17:15", updated_at: "2009-01-22 11:17:15">,
#<Task id: 3, project_id: 1, name: "Create demo app", due_at: nil, created_at: "2009-01-22 11:17:15", updated_at: "2009-01-22 11:17:15">,
#<Task id: 4, project_id: 1, name: "Scrutinize", due_at: nil, created_at: "2009-01-22 11:17:15", updated_at: "2009-01-22 11:17:15">]

>> project.author
=> #<Author id: 1, name: "Eloy", created_at: "2009-01-22 11:17:15", updated_at: "2009-01-22 11:17:15">

Now let's delete the first Task and change the name of the second Task:

>> project.tasks_attributes = { "1" => { "_delete" => "1" }, "2" => { "name" => "Who needs tests anyway?!" } }
=> {"1"=>{}, "2"=>{"name"=>"Who needs tests anyway?!"}}

>> project.tasks.first.marked_for_destruction?
=> true

>> project.tasks.forty_two
=> nil # Oops, I meant #second of course… ;)

>> project.tasks.second.name
=> "Who needs tests anyway?!" 

Finally, let's try to save the Project instance:

>> project.save
RuntimeError: Oh noes!
  from /Users/eloy/code/complex-form-examples/app/models/author.rb:9:in `raise_exception_if_needed'

An exception was raised while saving one of the nested models. Now let's see what happened to the data:

SQL (0.1ms)   BEGIN
Task Destroy (0.3ms)   DELETE FROM `tasks` WHERE `id` = 1
Task Update (0.2ms)   UPDATE `tasks` SET `updated_at` = '2009-01-22 11:22:23', `name` = 'Who needs tests anyway?!' WHERE `id` = 2
SQL (17.0ms)   ROLLBACK

As you can see, all changes were rolled back. Both updates as well as the removal of records marked for destruction all happen inside the same transaction.

As with any transaction, the attributes of the instance that you were trying to save will not be reset. This means that after this failed transaction the first task is still marked for destruction and the second one still has the new name value.

Conclusion

This patch allows you to create forms for nested model as deep as you would want them to be. Creating, saving, and deleting should all work transparently and inside a single transaction.

Please test this patch on your application, or take a look at my fork of Ryan's complex-form-examples which uses this patch.

Your feedback is much appreciated. However, keep in mind that we can't possibly satisfy everyone's needs all at once. Please suggest additional features or major changes as a separate ticket for after the patch has been applied. The goal is to fix the bugs in this patch first so we all have a clean foundation to build on.

On a final note, I would like to thank David Dollar for the original :accessible implementation, Fingertips (where I work) for sponsoring the time that has gone into this patch, Manfred Stienstra for extensive help on the documentation, and in no particular order Lance Ivy, Michael Koziarski, Ryan Bates, Pratik Naik and Josh Susser for general discussion.