我們想要達到的目標
我正在從 Nuxt.js 發送一個陣列,Rails 處于 API 模式,當我嘗試一一檢索和保存陣列內容時出現錯誤。我想保存 params 收到的陣列并添加多條記錄。
錯誤
ArgumentError (When assigning attributes, you must pass a hash as an argument, Array passed.):
代碼
控制器
def create
schedule = Schedule.new(post_params)
if schedule.save
render json: schedule, status: :created
else
render json: schedule, status: :internal_server_error
end
end
def post_params
params.require(:post).map do |schedule|
schedule.permit(:id, :name, :start, :end, :color, :timed, :long_time, :post_id, :post_item_id)
end
end
范圍
post: [,…]
0: {name: "", color: "#2196F3", start: 1648275300000, end: 1648276200000, timed: true, long_time: true}
1: {name: "", color: "#2196F3", start: 1648361700000, end: 1648362600000, timed: true, long_time: true}
2: {name: "", color: "#2196F3", start: 1648448100000, end: 1648449000000, timed: true, long_time: true}
3: {name: "", color: "#2196F3", start: 1648534500000, end: 1648535400000, timed: true, long_time: true}
4: {name: "", color: "#2196F3", start: 1648620900000, end: 1648621800000, timed: true, long_time: true}
我們嘗試了什么
?我嘗試使用 map 檢索值。
?我嘗試在pemit的末尾使用to_h將其轉換為哈希,但值和錯誤都沒有改變。
uj5u.com熱心網友回復:
Well first question here is what is happening if one of the records failed, do previously created should be rollbacked and following actions to be aborted or you just ignore invalid creations.
In case of rollback/aborting you can go for Schedule.create!(post_params) - responding with the proper message error and all others will be rollbacked.
In case of ignoring failure ones, go for Schedule.create!(post_params) - responding with created and failure ones.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/452378.html
