Skip to content

Instantly share code, notes, and snippets.

@maxivak
Last active December 30, 2015 15:29
Show Gist options
  • Save maxivak/7848662 to your computer and use it in GitHub Desktop.
Save maxivak/7848662 to your computer and use it in GitHub Desktop.
Rails Nested Forms Example - Formtastic, Cocoon. Tutorial is here - http://maxivak.com/rails-3-nested-models-in-one-form-using-formtastic-and-cocoon-gems/
CREATE TABLE IF NOT EXISTS `projects` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ;
CREATE TABLE IF NOT EXISTS `tasks` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`project_id` int(11) NOT NULL,
`title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ;
# app/views/projects/_form.html.haml
= semantic_form_for @project do |f|
- if @project.errors.any?
#form_errors.error
= f.semantic_errors :state
%h2
#{pluralize(@item.errors.count, "error")}:
%ul
- @project.errors.full_messages.each do |msg|
%li
= msg
= f.inputs :name => "Basic" do
= f.input :title
= f.input :description, :required => false, :input_html => { :style => "width:500px; height:120px;" }, :rows=>4
= f.inputs :name => "Tasks" do
= f.semantic_fields_for :tasks do |task|
= render "task_fields", :f => task
.links
= link_to_add_association 'Add task', f, :tasks
.clear
%br
%br
.form-group
= f.actions do
= f.action :submit, :as => :button
= f.action :cancel, :as => :link, :label => "Cancel"
# app/assets/javascripts/application.js
//= require cocoon
# app/models/project.rb
class Project < ActiveRecord::Base
attr_accessible :title, :description, :tasks_attributes
has_many :tasks, :dependent => :destroy
accepts_nested_attributes_for :tasks, :reject_if => lambda { |a| a[:title].blank? }, :allow_destroy => true
..
end
# app/models/task.rb
class Task < ActiveRecord::Base
attr_accessible :project_id, :title
belongs_to :project
validates_presence_of :title
..
end
# app/views/project/_task_fields.html.haml
.nested-fields
= f.inputs do
= f.input :title
= link_to_remove_association "Remove", f
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment