my territory model
class Territory < ActiveRecord::Base
attr_accessible :name, :publisher
has_many :addresses, :dependent => :destroy
validates :name, :presence => true, :uniqueness => true
end
my address model
class Address < ActiveRecord::Base
attr_accessible :name, :street, :district, :note
belongs_to :territory
end
I have a form for creating territories and a view to show a singe territory.
I've added a form for adding addresses to territories to the territory show view.
This is my address controlle开发者_Go百科r
class AddressesController < ApplicationController
def new
@address = Address.new
end
def create
@address = territory.addresses.build(params[:address])
if @address.save
flash[:success] = "Address saved!"
redirect_to '/territories'
else
redirect_to '/territories'
end
end
end
It looks that I can't get hold of the id of the current territory, hence can't connect the address to the territory. How can I do that?
Also, after the save I'd like to show the current view, i.e. a territory show view again. Not show how to do this redirect...
my routes
TerritoryManagement::Application.routes.draw do
resources :addresses
resources :territories
end
Thanks Thomas
You need to use nested resources for this, which is explained in the official Routing Guide. Another great example of this nested resources is in the official Getting Started Guide.
With this, you should receive a params[:territory_id]
variable in your AddressesController
when you make a new address for that territory, and from that you can then find the Territory
by doing this:
Territory.find(params[:territory_id])
But rather than me repeating it here, I would really recommend you read both those guides.
精彩评论