【问题标题】:Rails API: send request with nested resources through postmanRails API:通过邮递员发送带有嵌套资源的请求
【发布时间】:2018-09-12 13:15:04
【问题描述】:

我创建了一个只有 rails api 的应用程序。模型之间的关联如下:

class Book < ApplicationRecord
  has_and_belongs_to_many :authors
  accepts_nested_attributes_for :authors, allow_destroy: true
end 

class Author < ApplicationRecord
  has_and_belongs_to_many :books
end

现在,当我尝试使用邮递员发布的参数创建一个新的Book 时,

{
    "book": {
        "name": "Angels and Demons",
        "isbn": "12323012123213",
        "authors_attributes": [{"id": 1}, {"id": 2}]
    }
}

它给了我以下错误:虽然数据库中存在 ID 为 1 的作者。

"message": "找不到 ID=1 的作者 ID="

如果我更改了我的表单参数,如下所示:

{
    "book": {
        "name": "Angels and Demons",
        "isbn": "12323012123213",
        "authors_attributes": [{"0": {"id": 1}}, {"1": {"id": 2}}]
    }
}

它给了我来自Author 模型的验证错误。

控制器强参数:

def book_params
    params.require(:book).permit(:name, :isbn, authors_attributes: [:id, :_destroy])
  end

知道我做错了什么吗?

【问题讨论】:

  • @Mezbah,是的,我确实在问题上提到了这一点。

标签: ruby-on-rails postman nested-forms


【解决方案1】:

如果您想将一本书与现有作者相关联,则不需要嵌套属性 - 只需将一组 id 传递为 book_ids

{
    "book": {
        "name": "Angels and Demons",
        "isbn": "12323012123213",
        "author_ids": [1,2]
    }
}

ActiveRecord 将为所有 has_many 和 HABTM 关联创建 *association_name*_ids getter 和 setter。

仅当需要在同一请求中动态创建/更新相关记录时,才使用嵌套属性。对于 API 应用程序,我会避免嵌套属性,因为您最终会弯曲 Single Responsibility Principle

【讨论】:

  • 那么,在那种情况下我不需要accepts_nested_attributes_for?
  • 如果您只想将一条记录与其他现有记录关联,则不可以。
  • 对于 API 应用程序,您永远不会真正想要使用 accepts_nested_attributes_for。当您想将一堆功能塞入单个表单/请求中而不诉诸 ajax 时,它是经典 Web 应用程序的一种组合。
猜你喜欢
  • 2013-11-14
  • 2018-10-07
  • 1970-01-01
  • 2017-01-10
  • 1970-01-01
  • 1970-01-01
  • 2018-04-03
  • 2021-11-07
  • 2020-12-11
相关资源
最近更新 更多