我有以下型号:
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