UPDATE . This answer applies to Rails 2, or if you have special restrictions that require user logic. Mild cases are well resolved using name_fields, as discussed elsewhere.
Rails will not help you do much. This is contrary to standard viewing conventions, so you have to do workarounds in the view, controller, even routes. This is not fun.
Key resources for working with Rails multimodel forms are Stephen Chu params-foo series , or if you are on Rails 2.3 check out Nested Object Forms
It becomes much easier if you define some particular resource that you are editing, for example, Photoset. A Photoset may be a real model such as ActiveRecord, or it may simply be a facade that receives data and throws errors, as if it were an ActiveRecord model.
Now you can write a view form like this:
<%= form_for :photoset do |f|%> <% f.object.photos.each do |photo| %> <%= f.fields_for photo do |photo_form| %> <%= photo_form.text_field :caption %> <%= photo_form.label :caption %> <%= photo_form.file_field :attached %> <% end %> <% end %> <% end %>
Your model should check every child who enters the system and aggregate his mistakes. You can check out a good article on how to include checks in any class . It might look something like this:
class Photoset include ActiveRecord::Validations attr_accessor :photos validate :all_photos_okay def all_photos_okay photos.each do |photo| errors.add photo.errors unless photo.valid? end end def save photos.all?(&:save) end def photos=(incoming_data) incoming_data.each do |incoming| if incoming.respond_to? :attributes @photos << incoming unless @photos.include? incoming else if incoming[:id] target = @photos.select { |t| t.id == incoming[:id] } end if target target.attributes = incoming else @photos << Photo.new incoming end end end end def photos
Using the facade model for Photoset, you can easily and simply save the controller logic and view it by reserving the most complex code for the selected model. This code will probably not be exhausted, but hopefully it will give you some ideas and point you in the right direction to solve your question.
austinfromboston Jun 10 '09 at 0:43 2009-06-10 00:43
source share