views:

441

answers:

2

Is it possible to use select fields with nested object forms feature of Rails 2.3?

Example:

Suppose you have a Article model, Category model, and a ArticleCategories join model. Article has_many Categories through ArticleCategories.

On our Edit Article form, you want to have an HTML select list of all the available categories. The user can select one or more Category names to assign to the Article (multiple select is enabled).

There are lots of ways to do this, but I'm wondering if there is a simple way to accomplish this using the nested objects feature. What would the form look like in your view?

+1  A: 

Check out the nested form example from Github:

http://github.com/alloy/complex-form-examples

It's been a while since I looked at it, so I'm not sure if it covers exactly what you wanna do, but its a nice source for ideas / patterns.

reto
A: 

Assuming you have defined the models and their relationships so you can do this:

@art = Article.find(article_id)  
@art.categories # returns list of category objects this article is assigned to.

Then I usually use http://trendwork.kmf.de/175

You need to copy the JavaScript file into public/javascripts but after that you can just create the form element with something like:

swapselect(:article,@art,:categories,Category.find(:all).map { |cat| [cat.name, cat.id] })

(I would tend to wrap that in a helper to make the call even cleaner)

One small gotcha is that for very long lists it can run a little slow in IE6 because there's quite a lot of appendChild calls in the js which is notorioulsy slow in IE6

Update: Apologies. This doesn't really answer your original question, which was specifically about the Rails 2.3 feature. The swapselect option is version independent and doesn't make use of newer Rails functionality.

Julian Browne
swapselect is nice though. I used it in another project.
jaaronfarr