如何将一个视图中保存的对象ID传递给另一个视图?

时间:2013-05-19 19:09:21

标签: ruby-on-rails ruby

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

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

1 个答案:

答案 0 :(得分:1)

创建嵌套资源,因此load_id将位于网址中:/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/