【问题标题】:Update nested resource through API/Json通过 API/Json 更新嵌套资源
【发布时间】:2017-06-02 15:49:14
【问题描述】:

我正在构建一个 API 端点来更新模型。我可以更新除嵌套资源之外的每一列,我尝试了不同的方法,但似乎没有任何效果

这是我要发送到服务器的 JSON

{
"reservation": {
    "reservation_dates": [
        {
            "is_desirable": true,
            "date": "5-10-2019"
        }
         ]
  }
}

我从 reservation_date 获得了一个 unpermitted_pa​​ram,尽管我已将其添加到我的

def permitted_attributes_for_update
params.require(:reservation).permit(:date, :time, :comment, :budget, :currency, :status,
                                    :general_text, :idea_text, :artist_text, :desired_city,
                                    :desired_country, :desired_googleid, :studio_id, :artist_id,
                                    :tattoos, reservation_dates: [], general_url_array: [],idea_url_array: [],
                                    artist_url_array: [])
end

我希望能够直接从 JSON 更新,或者至少允许该数组,以便稍后在我的 UpdateService 上使用

感谢您的帮助

edit: this is the error I'm getting

【问题讨论】:

  • 用确切的错误更新问题。
  • 模型中是否允许嵌套属性?
  • 我有@8bithero

标签: ruby-on-rails json api ruby-on-rails-5


【解决方案1】:

您需要指定reservation_dates中允许的内容:

params.require(:reservation).permit(reservation_dates_attributes: [:is_desirable, : date], ...)

但是,请注意,如果您的 reservation has_many reservation_dates,那么这将导致冲突:reservation_dates 应该是 ReservationDate 的实例,但您提供的是哈希值。 rails 的方式是使用reservation_dates_attributes 而不是reservation_dates

【讨论】:

  • 我试过了。没有它,它会更新其他非嵌套字段。如果我将这些符号添加到我的许可证中,它会破坏整个事情
  • 查看更新,it breaks the whole thing 表示参数设法获得了权限,但它的存在引起了冲突。
  • 现在我得到“未经许可的参数::reservation_dates_attributes”
  • 我已经接受_nested_attributes_for :reservation_dates 到我的预订模型,并尝试了 :reservation_dates 和 :reservation_dates_attributes 到我的 .permit()
  • params permit 也需要更新:zparams.require(:reservation).permit(reservation_dates_attributes: [:is_desirable, : date], ...)`
猜你喜欢
  • 2015-11-17
  • 2020-11-10
  • 2016-12-11
  • 2016-05-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-22
相关资源
最近更新 更多