ruby 使用nested_attributes同步rails模型

qlckcl4x  于 2023-08-04  发布在  Ruby
关注(0)|答案(1)|浏览(80)

有没有可能更新一个rails模型,使其与该模型提供的嵌套属性同步?
假设我在LbriraryBook模型之间有一个多对多的关联:

class Library < ApplicationRecord
    #id integer
    #name string
    #location string

    has_many :library_books, dependent: :destroy
    has_many :books, through: :library_books

    accepts_nested_attributes_for :library_books, allow_destroy: true
end

class Book < ApplicationRecord
    #id integer
    #name string
    #author name

    has_many :libraries, through: :library_books
    has_many :library_books
end

class LibraryBook < ApplicationRecord
  # id integer
  # book_id integer
  # library_id integer

  belongs_to :library
  belongs_to :book
end

class LibrariesController < ApplicationController
  def update
    @library = Library.find(params[:id])
    if @library.update(library_params)
      # Successful update
    else
      # Handle errors
    end
  end

  private

  def library_params
    params.require(:library).permit(:name, library_books_attributes: [:id, :book_id])
  end
end

字符串
现在,我向LibrariesController发送一个请求,以创建一个新的Library记录沿着几本书:

{
  "id": 1,
  "library_books_attributes": [
      {
          id: 2
          book_id: 3
      }, 
      {
          book_id: 4
      },
      {
          book_id: 5
      }

  ],
  ...
}


我如何确保LibraryBook被更新,使得id为1的LibraryONLY匹配请求中的内容。因此,如果LibraryBook中已经存在book_id为12的记录,则该记录将被销毁,因为它不在library_books_attributes
因此,简而言之,无论子模型的请求中包含什么,都将始终是完整的列表,无论是否必须创建/更新/或删除记录。这是否可能与内置的活动记录/轨道功能,或者是需要写一个方法来做这个增量?

8dtrkrch

8dtrkrch1#

对于内置功能,您需要将该元素传入列表,如{ id: 12, _destroy: 1 }。对于您似乎想要的东西,您需要编写自己的library_books_attributes=方法。

相关问题