ruby-on-rails - 我们如何在使用 rails 中的 accepts_nested_attributes_for 关联更新后只获取新添加的对象

标签 ruby-on-rails ruby has-many accepts-nested-attributes

我的联想是这样的:

class Abc < ApplicationRecord
  has_many :def
  accepts_nested_attributes_for :def, allow_destroy: true
end

class AbcController < ApplicationController

  def update
    abc = Abc.find(params[:id])
     if abc.update(abc_params)
       # TODO Here update is sucessful but  how to get all newly added def in database with their id?
     end
  end


  private
  def abc_params
    params.require(:abc).permit(def_attributes: [:name, :title,:wordcount, :id])
  end
end

我们知道 accepts_nested 属性会在数据库中创建一个新的嵌套对象,那么我如何才能在 AbcController 更新函数中获取所有新添加的(尚未存在的)def 对象及其数据库 ID?

最佳答案

一个解决方案是(不是直接的)..

def update
  abc = Abc.find(params[:id])
  number_of_defs = abc.defs.length
  if abc.update(abc_params)
    number_newly_added_defs = abc.defs.length - number_of_defs
    newly_added_defs = abc.defs.last(number_newly_added_defs)
  end
end

您将获得所需的输出。

关于ruby-on-rails - 我们如何在使用 rails 中的 accepts_nested_attributes_for 关联更新后只获取新添加的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43887278/

相关文章:

ruby-on-rails - 有没有办法打包我的 gem 依赖于我的 gem 的所有 gem ?

php - 显示表中的一列在 Laravel 中有很多关系

css - Rails 4 image_tag 不从 Assets 加载图像

ruby-on-rails - 如何清除 Rails 控制台历史记录

ruby-on-rails - RSpec stub 邮件程序

ruby - 请解释 Ruby 如何解释数字

ruby - 在 Heroku 的 Amazon S3 上调整图像大小

javascript - 一种形式中有多个隐藏字段?

ruby-on-rails-4 - 通过 has_many 关联的 rails 范围

mysql - 数据库驱动应用程序中的 Has_Many、Belongs_To 关系