Skip to content

Instantly share code, notes, and snippets.

@jamilbk
Forked from robertwclark/nestedform
Created December 1, 2012 02:58
Show Gist options
  • Save jamilbk/4180347 to your computer and use it in GitHub Desktop.
Save jamilbk/4180347 to your computer and use it in GitHub Desktop.
Nested Form Build
class Organization < ActiveRecord::Base
attr_accessible :name, :employee_number, :country, :postal_code, :sic_code, :primary_url, :social_entities_attributes, :social_channels_attributes
has_one :user
has_one :social_score, :through => :social_entities
has_many :social_entities
has_many :social_channels, :through => :social_entities
accepts_nested_attributes_for :social_entities, :social_channels
end
class SocialEntity < ActiveRecord::Base
attr_accessible :name, :org_id, :social_channel_attributes
has_many :social_channels
has_many :social_scores
belongs_to :organization
accepts_nested_attributes_for :social_channels
class SocialChannel < ActiveRecord::Base
attr_accessible :authorized, :channel_identifier, :channel_type, :name, :social_entity_id
belongs_to :social_entities
end
class OrganizationsController < ApplicationController
def new
@organization = Organization.new
@social_entities = @organization.social_entities.build
@social_channels = @social_entities.social_channels.build
end
def create
@organization = Organization.new(params[:organization])
current_user.org_id = @organization.id
if @organization.save
flash[:notice] = "You have created a new organization"
flash[:color]= "valid"
else
flash[:notice] = "Form is invalid"
flash[:color]= "invalid"
end
redirect_to(:controller => 'sessions', :action => 'home')
end
end
<%= form_for(:organization, :url => {:controller => 'organizations', :action => 'create'}) do |f| %>
<label>Organization Name:</label> <%= f.text_field :name%>
<%= f.fields_for :social_entities do |builder| %>
<%= f.fields_for :social_channels do |builder| %>
<%= builder.label :name, "Twitter" %><%= builder.text_field :name%>
<% end %>
<% end %>
<br />
<%= f.submit :create %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment