Join GitHub today
GitHub is home to over 28 million developers working together to host and review code, manage projects, and build software together.Sign up
Small demo to show creating or selecting an associated object
Fetching latest commit…
Cannot retrieve the latest commit at this time.
|Type||Name||Latest commit message||Commit time|
|Failed to load latest commit information.|
== 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/