Rails 使用 accepts_nested_attributes_for 去 update 一对多的嵌套表,为什么 update 变成了 insert

Runable · March 15, 2019 · Last by Runable replied at March 18, 2019 · 1946 hits
def update
  @diary=Diary.find(params[:id])
  if @diary.update(update_diary_params)
    render_ok
  else
    render_err :update_error
  end
end
def update_diary_params
  params.require(:diary).permit(:date,:weather,:remark, :diary_pictures_attributes=> [:diary_picture,:clothing_picture,:id,:_destroy])
end
class Diary < ApplicationRecord
  has_many :diary_pictures,dependent: :destroy

  accepts_nested_attributes_for :diary_pictures,allow_destroy: true

end

class DiaryPicture < ApplicationRecord
  belongs_to :diary
  validates_presence_of :diary
end

为什么不是 update 是 insert?

params 自己输出一下

id 有传上来吗?

Reply to zj0713001

参数可以获取到,但是 update 的时候变成了 insert

Reply to Rei

:diary_pictures_attributes=> [:diary_picture,:clothing_picture,:id,:_destroy],这里的:id 可以获取到吗?

Reply to Rei

有更新 diary 的内容,但是到了 diary_picture 就不是 update 了,变成了 insert

在终端模拟一下 update 看模型设置和参数有没有问题。把 controller 过滤后的 params 打印出来看看合不合预期。

Reply to Runable

update 的 action 里 binding.pry 打断点 然后输出 params 贴出来~

是这个错误吗?

你这个里面的 id 并不是嵌套表单里面的 id,取到数据的时候自然找不到原有的数据去 update,所以每次都是进行 insert 操作

diary_pictures_attributes 数组项里没有 id。

可能是 form 没写好,用 fields_for 会自动帮你输出 id field

<%= form.fields_for :dirary_pictures do |pic| %>
<% end %>

问题找到了,感谢大家,是 id 的问题,他找不到 id 就自己创建了

Runable closed this topic. 18 Mar 17:48
Runable reopened this topic. 18 Mar 17:49
You need to Sign in before reply, if you don't have an account, please Sign up first.