Skip to content

Instantly share code, notes, and snippets.

@samiron
Created October 5, 2012 18:24
Show Gist options
  • Save samiron/3841507 to your computer and use it in GitHub Desktop.
Save samiron/3841507 to your computer and use it in GitHub Desktop.
Rails 3: Nested form_for child field_for parent
#Description: We want to show a region(parent) form
#while showing City information.
#If the form submitted with Region information,
# - New region will be created
# - City#region_id will have the new region id
def show
@city = City.find(params[:id])
@region = @city.build_region
respond_to do |format|
format.html # show.html.erb
format.json { render json: @city }
end
end
#Note: This is just the default method provided by a scaffold.
#Nothing special needed to handle this.
def update
@city = City.find(params[:id])
respond_to do |format|
if @city.update_attributes(params[:city])
format.html { redirect_to @city, notice: 'City was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @city.errors, status: :unprocessable_entity }
end
end
end
#Models/City.rb
class City < AciveRecord::Base
belongs_to :region
accepts_nested_attributes_for :region #<---- This line will do the trick in cities_controller#update method
end
#Models/Region.rb
class Region < AciveRecord::Base
has_many :cities
end
#Defining the regions resource
resources :regions do
#This part doesn't really have any effect in this case
#But in our example application, city is a nested resource
#region
resources :cities
end
#City is also a independent resource.
#This way we can access /cities/1
resources :cities
#NOTE: Run `rake:routes` to see the output
<!--
This is the form to enter new Region information.
-->
<%= form_for(@city) do |f|%>
<%= f.fields_for(:region) do |fr|%>
<%= fr.text_field :name%>
<% end %>
<%= f.submit 'Submit'%>
<% end %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment