Create New Records With Bootstrap Modal and Rails Unobtrusive Javascript
I wanted the quickest way to get a nice looking modal popover, in which to create a new record, and after the modal dismisses, the new record to show up. All without the page refreshing.
And let’s throw in validations in the modal as well.
Say you have a simple model (Post) with some fields.
1 2 3 |
|
Add client_side_validations to take care of validations for us (only gem we’re going to use, I promise…except haml-rails so you can actually read HTML)
1
|
|
Run the install generator for client_side_validations
1
|
|
Add the rails.validations.js to your layout
1
|
|
Now, we need to download Bootstrap. I recommend customizing it with the cool things you want on this page. If that fails, the minified full version is only 48k. Make sure you copy the javascripts, css, and images into your assets directory accordingly.
We’ll just edit ‘app/views/posts/index.html.haml’ for this example so that it’s all in one file. However, it’s good practice to render each modal in a different file.
Change your ‘Add Post’ button to this:
1
|
|
The data-toggle tells Bootstrap this link toggles the modal. The href tells it the ID of the modal element it toggles.
Here’s our modal:
1 2 3 4 5 6 7 8 9 10 11 12 |
|
The validate: true
makes sure we use the client_side_validations we added earlier. remote: true
tells it to use Rails’ Unobtrusive Javascript.
The html: {"data-type" => :json})
specifies that we want the controller to return JSON back to the view.
The classes (modal, hide, fade) declare it as a modal that is hidden at first, and then fades in.
With the latest Rails, we don’t need to change anything in the controller. Here’s what my create action looks like:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
The only thing we need to do is to make sure we are listening for when the JSON comes back, so that we can dismiss the modal, and show the new data.
1 2 3 4 |
|
In the case above, we dismiss the modal and then insert a new row in a table with the title and content of the post we just added.
I tried to keep this as simple as possible. Hope it helps.