Single forms that create multiple models

I've been following along with the Yelpdemo course (modifying it to fit my own use case/project) and wanted to know how I could build a form that creates a restaurant and a review in one go? Imagine the user searches for a restaurant and it doesn't exist on the system, I'd like them to be able to create the restaurant and leave a review from the same view. I still want the user to be able to click through from a restaurant to leave a review against an existing restaurant too though. Any help would be really appreciated. Thanks Dan

Posted over 4 years ago by Dan Tidmas
Posted over 4 years ago by Alex Yang

There are a couple different ways to approach this. You can either have two separate forms with different inputs depending on whether the restaurant already exists, or you can have a single, dynamic form that can optionally have the form fields for adding a new restaurant. In the second case, you'd need to check from your controller which fields were filled in so you can tell whether you need to add a new restaurant. The second approach is a bit more complicated, so if you're relatively new to Rails, I'd recommend using the first approach.

I'd leave the main 'Add Review' button linking to the original review form and add another button (either on a different page or somewhere else on the same page) to link to the form to add a restaurant and a review. To set up the new form, I recommend following the same approach that you see in the default Rails form. In other words, you'll need to add your view pages (similar to _form.html.erb), controller actions (similar to 'new' and 'create'), and finally set up your routes.rb file to add in the two new actions you've set up. Here's a very thorough resource to learn more about routes: Try it out and let me know how it goes!