Small demo to show creating or selecting an associated object
Ruby JavaScript
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
app
config
db
doc
lib/tasks
public
script
test
vendor/plugins
.gitignore
Gemfile
Gemfile.lock
README
Rakefile
config.ru

README

== Create or Select

I wanted a form field that I could have a user fill in, and it would either select the matching thing (as in a select box) or create a new one with the attribute.

For instance, if you have say, our friend the blog, and that has Post which belongs_to Category.  My goal was a text field for category (as opposed to the usual select) that will allow both an existing value, or a new one.

I also wanted it to be safe. My first attempts at this ended rather poorly, and just didn't feel right. I tried both some madness on the models, and some transactions in the controller when saving.  The transactions do work, but you wind up with a lot of book keeping for such a small thing.

The approach I settled on (as you will see) is using nested attributes, but in reverse. All the examples I found assumed you wanted the has_many end of the relation in the form.  Some time in irb later, I nailed it. (Or got it working, anyway)

A bit more detail at http://ajvargo.com/2010/10/create-or-select-a-value-via-nest-resources/