开发者

creating subrecords in rails 3

开发者 https://www.devze.com 2023-03-30 06:27 出处:网络
my territory model class Territory < ActiveRecord::Base attr_accessible :name, :publisher has_many :addresses, :dependent => :destroy

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消