Tweaks to scaffolding for adding "child" rows by jgn on Thursday, August 30, 2007 in Technology and Rails

There are times when you need to use a bit of Rails scaffolding to get up and running and for various reasons you don't want to resort to ActiveScaffold or some other medium-weight strategy. All you want to do is provide the user a means to see a "master" row, and then allow for adding a row to a dependent ("child") table. Here we're talking about "the simplest thing that could possibly work." This example is for Rails 1.2.3.

Typically the recipe is going to be like so:

Add your scaffolds:

script generator/scaffold master Admin::Master
script generator/scaffold child Admin::Child

Edit your migrations to get your data model where you want it.

In master/show.rhtml, add ruby <%= link_to 'Add child', :controller => Admin::Child, :action => 'new', :id => %> <br/><br/>

In child/_form.rhtml, add ruby <%= hidden_field 'child', 'master_id', :value => params[:id] %>

That's essentially it. Now after adding a Master record, you click the scaffold's "show" link, and that view will give link to add a Child record with its foreign key set to the value of the Master for which you are adding the Child.

As soon as it gets complicated, though, go use ActiveScaffold.

comments powered by Disqus