Rails嵌套表单不更新
我在获取update_attributes以更新表单中的嵌套模型时遇到问题。 我没有任何错误,但嵌套属性不保存。 这是相关的代码:
用户型号:
class User < ActiveRecord::Base has_many :orders has_many :achievements accepts_nested_attributes_for :achievements
成就模型:
class Achievement < ActiveRecord::Base belongs_to :user
编辑用户表单:
{ :multipart => true } do |f| %>
…
编辑方法:
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数组时,即使我填写表单,它也总是空的。 有谁知道我做错了什么?
您应该更改为accepts_nested_attributes_for :achievements_attributes
。 您可以检查日志文件中表单post的参数,以查看rails如何命名表单元素。 或者检查页面上的HTML。
在用户模型中:
attr_accessible :achievements_attributes
好像工作:)