Search code examples
rubyruby-on-rails-3.1

How to use last created forms values for new form?


I have the follow models:

User
 has_many :armies

Army
 belongs_to :user

My controller with the added current_user:

class ArmiesController < ApplicationController
  before_filter :authenticate_user!
  def new
    @army = Army.new
  end

  def create
    @army = current_user.armies.new(params[:army])
    respond_to do |format|
      if @army.save
        format.html { redirect_to new_army_path, :notice => "New army added" }
      else
        format.html { render :new }
      end
    end
  end
end

I want to use my last created forms value for the new one. We'll use my strength field as an example:

<%= form_for @army do |f| %>
   <%= f.label :strength, "Army Strength" %>
   <%= f.text_field :amount %>
   <%= f.submit "Create" %>
<% end %>

How can I save the value that the user input's in the strength field so it remains on the form after the last form is created?

EDIT:

  def new
    @army = Army.new(strength: session[:last_army_strength], 
                     type_id: session[:last_type])
  end

  def create
    @army = current_user.armies.new(params[:army])
    session[:last_army_strength] = params[:army][:strength]
    session[:last_type] = params[:army][:type_id]
    respond_to do |format|
      if @army.save
        format.html { redirect_to new_army_path, :notice => "New army added" }
      else
        format.html { render :new }
      end
    end
  end
end

Solution

  • I think this should work:

    class ArmiesController < ApplicationController
      before_filter :authenticate_user!
      def new
        @army = Army.new(strength: session[:last_army_strength])
      end
    
      def create
        @army = current_user.armies.new(params[:army])
        session[:last_army_strength] = params[:army][:strength]
        respond_to do |format|
          if @army.save
            format.html { redirect_to new_army_path, :notice => "New army added" }
          else
            format.html { render :new }
          end
        end
      end
    end