Embeds_many child 属性 保存时未保留 parent

Embeds_many child property not persisted when saving parent

我找了好几天都没有找到我的问题的确切答案,这个答案就这么简单:我有一个简单的模型,有书和作者。一本书嵌入了许多作者,而作者嵌入在书中。但是每当我保存一本新书时,作者数组就不会保留。

我有一个 angular 7 应用程序,调用了一个 ROR API。我的 Rails 版本是 5.2.2。我正在使用 mongoid 7.0 进行持久化。

我的 API 是使用 rails g 脚手架以及 --api 和 --skip-active-record 标志生成的。

我首先遇到了属性映射问题。当 Rails 等待表单 lower_snake_case 变量时,我的 Angular APP 以小驼峰形式发送 JSON。我设法通过在我的初始化器中添加一个中间件(如果我在这个上错了请纠正我)来绕过这个问题,它将 camelCase 转换为 snake_case.

# Transform JSON request param keys from JSON-conventional camelCase to
# Rails-conventional snake_case:
ActionDispatch::Request.parameter_parsers[:json] = -> (raw_post) {
   # Modified from action_dispatch/http/parameters.rb
   data = ActiveSupport::JSON.decode(raw_post)
   data = {:_json => data} unless data.is_a?(Hash)

   # Transform camelCase param keys to snake_case:
   data.deep_transform_keys!(&:underscore)
}

根据我发现的问题,这可能是强参数的问题,所以我试图在我的 book_params

中解决这个问题
def book_params
  #params.fetch(:book, {})
  params.require(:book).permit(:title, :release_date, authors_attributes: [:name, :last_name, :birth_date])
end

这些是我的模型:

class Person
  include Mongoid::Document
  field :last_name, type: String
  field :first_name, type: String
  field :birth_date, type: Date
end

class Author < Person
  include Mongoid::Document
  embedded_in :book
end

class Book
 include Mongoid::Document
 field :title, type: String
 field :release_date, type: Date
 embeds_many :authors 
 accepts_nested_attributes_for :authors
end

这是我的图书控制器中的 POST(使用 Rails 生成)

  # POST /books
  def create

    @book = Book.new(book_params)

    if @book.save
      render json: @book, status: :created, location: @book
    else
      render json: @book.errors, status: :unprocessable_entity
    end
  end

下面是发送、接收的正文以及 Rails 如何处理的示例:

Request sent by angular app

Request received and processed by Rails

我们可以在书上看到object

"book"=>{"title"=>"azerty", "release_date"=>"2019-01-21T16:10:19.515Z"}}

作者已经消失,尽管他们出现在服务器收到的请求中。

我的问题是:解决这个问题的方法是什么,或者至少我缺少什么? Mongoid 在使用嵌入文档和 accepts_nested_attributes_for 时不会自动保存 children 吗?每次在我的控制器中保存 parent 时,我是否应该手动保存 children?

在此先感谢您对我的帮助

您必须使用嵌套属性来保存子记录

book 模型中添加以下行

accepts_nested_attributes_for :authors

并在 author_attributes 中传递作者参数,例如:

{title: 'test', release_date: '', author_attributes: [{first_name: '', other_attributes of author}, {first_name: '', , other_attributes of author}]}

更多详情请查看Mongoid: Nested attributes

以这种格式传递参数

{"title"=>"test", "release_date"=>"2019-01-22", "book"=>{"title"=>"test", "release_date"=>"2019-01-22", "authors_attributes"=>[{"first_name"=>"test name", "last_name"=>"test", "birth_date"=>"2019-01-22T09:43:39.698Z"}]}}

允许书籍参数

def book_params
   params.require(:book).premit(:first_name, :last_name, authors_attributes: %i[first_name last_name birth_date])
end