0

我有以下型号:

User
 has_many :armies

Army
 belongs_to :user

我的控制器添加了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

我想将上次创建的表单值用于新的表单值。我们将以我的strength领域为例:

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

如何保存用户在strength字段中输入的值,以便在创建最后一个表单后保留在表单上?

编辑:

  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
4

1 回答 1

1

我认为这应该有效:

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
于 2012-08-07T14:03:56.267 回答