Building a Multi-Model Form


Notice: A non well formed numeric value encountered in /home/batteur/www/wp-content/plugins/crayon-syntax-highlighter/crayon_formatter.class.php on line 118

Notice: A non well formed numeric value encountered in /home/batteur/www/wp-content/plugins/crayon-syntax-highlighter/crayon_formatter.class.php on line 119

Notice: A non well formed numeric value encountered in /home/batteur/www/wp-content/plugins/crayon-syntax-highlighter/crayon_formatter.class.php on line 118

Notice: A non well formed numeric value encountered in /home/batteur/www/wp-content/plugins/crayon-syntax-highlighter/crayon_formatter.class.php on line 119

Notice: A non well formed numeric value encountered in /home/batteur/www/wp-content/plugins/crayon-syntax-highlighter/crayon_formatter.class.php on line 118

Notice: A non well formed numeric value encountered in /home/batteur/www/wp-content/plugins/crayon-syntax-highlighter/crayon_formatter.class.php on line 119

Notice: A non well formed numeric value encountered in /home/batteur/www/wp-content/plugins/crayon-syntax-highlighter/crayon_formatter.class.php on line 118

Notice: A non well formed numeric value encountered in /home/batteur/www/wp-content/plugins/crayon-syntax-highlighter/crayon_formatter.class.php on line 119

Your application must interact with more than one model on a single form. Rails offers this support for nested forms.

Take the case that one wishes to label the posts of a blog with tags.
We assume the posts module and its controller are already available.

To demonstrate, we will allow you to add multiple tags to each post. Start by creating a new model to hold the tags:

run the migration to create the table in the database.

Then edit the file to associate post.rb tag to posts and to tell Rails (via macro accepts_nested_attributes_for) you want to edit tags via posts:

Option: allow_destroy on the declaration of nested attributes tells Rails to display a checkbox “remove” in the next view. The reject_if option prevents saving tags without attributes.

Then modify views / posts / _form.html.erb to make a partial tag creation:

Tags :