user2297820
user2297820

Reputation: 3

How to I pass a object ID saved in one view to another view?

I am using Rails to build an app as follows. I want to create a Load with multiple stops. I have a class Load with "has_many :stops". Once the load structure is created I save the load and take the user to new stop view. How do I take the load Id that was created in the last click and pass it on to the stop? Here is what I have in new stop.

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

Upvotes: 0

Views: 154

Answers (1)

michelpm
michelpm

Reputation: 1845

Create a nested resource, so the load_id will be in the URL: /loads/:load_id/stops/new.

In the Load model:

class Load < ActiveRecord::Base
  has_many :stops
end

Routes:

resources :loads do
  resources :stops
end

Controller for stops:

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

Extracted from here:

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

Upvotes: 1

Related Questions