Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source

Ticket #3880 (new enhancement)

Opened 2 years ago

Last modified 1 year ago

[PATCH] Nested Object Support in Form Helper

Reported by: seangeo@gmail.com Assigned to: David
Priority: normal Milestone: 2.x
Component: ActionPack Version: 1.0.0
Severity: normal Keywords: risky
Cc:

Description

Hi

I have made a patch to form_helper.rb that adds support for building input elements for nested objects. For example, if a Post class has an author attribute that has a Person class as it's value you can now go form_helper('post', 'author.name') to create an input field that has the author.name as its value and post[author][name] as its name and post_author_name as its id.

This allows form helper to be more useful when dealing with nested objects. Hopefully someone else will find it useful.

It has some shorting coming... auto-indexing does not yet work for nested objects but this could be added.

BTW, its my first Rails patch so be gentle. ;)

Cheers

Attachments

nested_form_helper.patch (4.6 kB) - added by seangeo@gmail.com on 02/18/06 18:06:27.

Change History

02/18/06 18:06:27 changed by seangeo@gmail.com

  • attachment nested_form_helper.patch added.

02/20/06 03:17:53 changed by david

  • keywords set to risky.

Could you explain how you're using this in for example an update action? Since person.author doesn't exist by default, then Person.new(params[:person]) wouldn't work.

02/20/06 09:36:48 changed by seangeo@gmail.com

I think you mean post.author right?

I'll agree that the example provide probably isn't the most useful or clear since you probably wouldn't be editing author details when editing a post, I just used it since that was the fixtures used in the form_helper test case.

To provide a better example, given a Person class that has a has_one address property that points to an Address class with street and post_code properties, this change would allow you to use the form helper to create a form that lets you edit a persons address while editing their other details, like this:

text_field 'person', 'address.street'
text_field 'person', 'address.post_code'

as opposed to

@address = person.address
text_field 'address', 'street'
text_field 'address', 'post_code'

However, I think your point about the ugliness in the controller is correct and this patch might also require changes to attributes= in ActiveRecord::Base to propagate changes to associated objects for subhashes in the params hash and in this case create an Address instance and assign to self.address if it doesn't already exist. I can look at adding this change to the patch if you are interested.

Does that answer your questions?

03/06/07 11:17:28 changed by bitsweat

  • milestone set to 1.x.

Neat idea, worth pursuing..