嵌套表单丢失数据
遗憾的是,在验证用户输入的数据失败后,我的表单丢失了。我该如何更改此设置,以便表单不会丢失数据?
查看_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
感谢您的帮助!
Sadly loses my form after unsuccessful validation the data which have the user typed in. How can I change this, so that the form doesn't losing the data?
View _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>
Controller 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
Thanks for your help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
解决方案是将实例变量设置为值,如以下代码所示。
The solution is to set an instance variable as value like the following code.
使用:
<%= f.fields_for @table1 do |ff| %>
确保使用从表单提交接收到的数据在控制器中设置
@table1
。Use:
<%= f.fields_for @table1 do |ff| %>
Make sure that
@table1
is set in the controller with the data that is received from the form submission.最好使用
您不必设置值,即
<% ff.text_field :name, value: 'something' %>
。Is better to use
You won't have to set values, i.e.
<% ff.text_field :name, value: 'something' %>
.