Skip to content

Instantly share code, notes, and snippets.

@madwork
Last active December 12, 2015 06:38
Show Gist options
  • Save madwork/4731124 to your computer and use it in GitHub Desktop.
Save madwork/4731124 to your computer and use it in GitHub Desktop.
nested attributes with dynamic form
class Contact < ActiveRecord::Base
has_many :responses
has_many :dynaforms, through: :responses
attr_accessible :email, :responses_attributes
accepts_nested_attributes_for :responses
def self.new_with_dynaforms
new.tap do |contact|
Dynaform.all.each do |dynaform|
contact.responses.build dynaform: dynaform, dynaform_name: dynaform.form_name, dynaform_type: dynaform.form_type
end
end
end
end
class Dynaform < ActiveRecord::Base
has_many :responses
has_many :contacts, through: :responses
attr_accessible :form_type, :form_name
end
<% @contacts.each do |contact| %>
<div>
<strong><%= contact.email %></strong><br />
<% contact.responses.each do |response| %>
<%= response.form_name %> : <%= response.value %><br />
<% end %>
</div>
<% end %>
<%= form_for @contact, url: responses_path do |f| %>
<div>
<%= f.label :email %>
<%= f.text_field :email %>
</div>
<%= f.fields_for :responses do |response_fields| %>
<div>
<%= response_fields.label :value, response_fields.object.dynaform_name %>
<%= response_fields.send(response_fields.object.dynaform_type, :value) %>
<%= response_fields.hidden_field :dynaform_id %>
</div>
<% end %>
<%= f.submit %>
<% end %>
class Response < ActiveRecord::Base
belongs_to :contact
belongs_to :dynaform
attr_protected :contact_id
validates_presence_of :dynaform
attr_accessor :dynaform_name, :dynaform_type
def dynaform_name
dynaform.try(:form_name)
end
def dynaform_type
dynaform.try(:form_type)
end
end
class ResponsesController < ApplicationController
def index
@contacts = Contact.all(:include => :attributes)
end
def new
@contact = Contact.new_with_dynaforms
end
def create
@contact = Contact.new params[:contact]
if @contact.save
redirect_to responses_url
else
render action: :new
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment