Rails嵌套表单未更新 [英] Rails Nested Forms Not Updating
问题描述
我在获取update_attributes来更新表单中的嵌套模型时遇到问题.我没有任何错误,但是嵌套属性没有保存.这是相关的代码:
I'm having a problem getting update_attributes to update nested models in my form. I don't have any errors but the nested attributes aren't saving. Here's the relevant code:
用户模型:
class User < ActiveRecord::Base
has_many :orders
has_many :achievements
accepts_nested_attributes_for :achievements
成就模式:
class Achievement < ActiveRecord::Base
belongs_to :user
编辑用户表单:
<%= form_for @user, :html => { :multipart => true } do |f| %>
...
<%= f.fields_for :achievements do | a | %>
<%= a.label :title %>
<%= a.text_field :title %><br>
<% end %>
编辑方法:
def edit
@user = nil
if params[:id] != nil
@user = User.find(params[:id])
elsif
@user = current_user
else
redirect_to login_path
end
5.times { @user.achievements.build }
end
更新方法:
@user.update_attributes params[:user]
但是当我检查@ user.achievements数组时,即使我填写表格,它也总是空的.有人知道我在做什么错吗?
But when I check the @user.achievements array it's always empty even when I fill out the forms. Does anyone know what I'm doing wrong?
推荐答案
您应更改为accepts_nested_attributes_for :achievements_attributes
.您可以检查日志文件中表单帖子的参数,以了解Rails如何命名表单元素.或检查页面上的HTML.
You should change to accepts_nested_attributes_for :achievements_attributes
. You can inspect the parameters for the form posts in your log file to see how rails named the form elements. Or inspect the HTML on your page.
这篇关于Rails嵌套表单未更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!