0

我正在使用 Rails 构建一个应用程序,如下所示。我想创建一个具有多个站点的负载。我有一个带有“has_many :stops”的类加载。创建负载结构后,我会保存负载并将用户带到新的停止视图。如何获取在最后一次单击中创建的负载 ID 并将其传递给停止?这是我在新站的内容。

<%= label_tag :load_id %><br />
<%= number_field_tag :load_id %>
4

1 回答 1

1

创建一个嵌套资源,因此 load_id 将位于 URL:/loads/:load_id/stops/new中。

在负载模型中:

class Load < ActiveRecord::Base
  has_many :stops
end

路线:

resources :loads do
  resources :stops
end

停止控制器:

class StopsController < ApplicationController
  # get /loads/:load_id/stops/new
  def new
    load = Load.find(params[:load_id])
    @stop = load.stops.build
  end
  # post /loads/:load_id/stops
  def create
    load = Load.find(params[:load_id])
    @stop = load.stops.create(params[:stop])
    if @stop.save
      format.html { redirect_to([@stop.post, @stop], :notice => 'Stop was successfully created.') }
    else
      format.html { render :action => "new" }
    end
  end
end

从这里提取:

http://blog.8thcolor.com/2011/08/nested-resources-with-independent-views-in-ruby-on-rails/

于 2013-05-19T19:55:26.990 回答