我正在使用Rails和React。我有两个型号:schedule
和worker
。 worker belongs_to schedule
和schedule has_many workers
。我想从反应中对rails进行更新请求。如何更新Rails中的所有关联模型?
这是fetch
功能是什么样子,我用它来发送请求:
function updateSchedule(scheduleId, date, message, workersArray, cb){
return fetch(`api/schedules/${scheduleId}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
date: date,
message: message,
user_id: 1,
worker_info: workersArray
})
}).then((response) => response.json())
.then(cb);
}
workersArray的样本:
[{"id"=>54, "name"=>"Owen
Johnston", "phone"=>"111-222-3333", "created_at"=>"2017-06-13T22:17:45.769Z", "updated_at"=>"2017-06-13T22:17:45.769Z", "schedule_id"=>33}, {"id"=
>55, "name"=>"Mary Watson", "phone"=>"123-456-7890", "created_at"=>"2017-06-13T22:17:45.778Z", "updated_at"=>"2017-06-13T22:17:45.778Z", "schedule_
id"=>33}]
计划有日期,消息和USER_ID属性。附表还有一组特定的工作人员。每名工人都有一个name
和phone
。简而言之,在特定的时间表上,我想更新时间表的属性,包括其中的所有工作人员姓名和电话。我有问题遍历所有属于该时间表的工作人员并更新每个工作人员的参数。
这是一般的想法。我有问题使update
方法工作。
def update
@schedule = Schedule.find(params[:id])
if @schedule.update_attributes(schedule_params)
worker_params["worker_info"].each do |w|
@worker = Worker.find(w.id)
@worker.update_attributes!
end
render json: @schedule
else
render json: @schedule, status: :unprocessable_entity
end
end
...
def schedule_params
params.require(:schedule).permit(:date, :message, :user_id)
end
def worker_params
params.permit(worker_info: [:name, :phone])
end
如何发送一个PUT请求从反应轨并告诉Rails更新相关的进度计划和所有的工人呢?
我没有看到任何从请求主体进来的'schedule_params'。 –