遗憾的是,在验证用户输入的数据失败后,失去了我的表单。我如何改变这一点,使表单不会丢失数据?
视图_form.html.erb:
<%= form_for(@user, :html => {:name => "newUser""}) do |f| %>
<div class="field_left">
<%= f.label :last_name, "Last name<span>*</span>".html_safe %><br />
<%= f.text_field :last_name %>
</div>
<% end %>
<div class="field">
<%= f.fields_for :table1 do |ff| %>
<%= ff.text_field :name %>
<% end %>
</div>
控制器users_controller:
def new
@user = User.new
1.times {@user.table1.build}
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @user }
end
end
def create
@user = User.new(params[:user])
@table1= params[:user][:table1][:name]
respond_to do |format|
if @user.save
format.html { redirect_to(@user, :notice => 'User was successfully created.') }
format.xml { render :xml => @user, :status => :created, :location => @user }
else
format.html { render :action => "new" }
format.xml { render :xml => @user.errors, :status => :unprocessable_entity }
end
end
end
谢谢你的帮助!
解决方案是像下面的代码一样设置一个实例变量作为值。
<%= f.fields_for :table1 do |ff| %>
<%= ff.hidden_field :name, :value => @value %>
<% end %>
使用:<%= f.fields_for @table1 do |ff| %>
确保控制器中的@table1
与从表单提交接收到的数据一起设置。
最好使用
<%= f.fields_for :table1, f.object.table1 do |ff| %>
<% ff.text_field :name %>
<% end %>
您不需要设置值,即<% ff.text_field :name, value: 'something' %>