Rails와 React를 사용하고 있습니다. 두 가지 모델이 있습니다 : schedule
및 worker
. worker belongs_to schedule
및 schedule has_many workers
. 반응에서 레일에 업데이트 요청을하고 싶습니다.
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);
}
workerArray 샘플 :
[{"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
react에서 rails로 put 요청을 보내고 Rails에게 일정 및 일정과 관련된 모든 작업자를 업데이트하도록하려면 어떻게해야합니까?
Rails로 보내는 내용에 차이가 있지만 올바른 매개 변수를 보내고 일정을 업데이트 할 수 있다고 가정 해 보겠습니다 (근로자 제외). 불일치는 schedule
매개 변수에 키를 보내는 것이 아니라 다음 줄에 필요하다는 것입니다.
params.require(:schedule).permit(:date, :message, :user_id)
최종 JSON (rails로 보내는)이 다음과 같은지 확인하십시오.
{
"schedule": {
"date": "...your date",
"message": "...message",
"user_id": "...user_id"
}
}
내가 생각하는 실제 문제에 도달하는 것은 작업자를 업데이트 할 수 없다는 것입니다. Rails에는 고통을 덜어 줄 모델에 대한 특별한 지침이 있습니다.
당신의에서 Schedule
모델 작성 :
accepts_nested_attributes_for :workers, allow_destroy: true
이렇게하면 모델이 하위 속성도 업데이트 할 수 있습니다. 이 후에 컨트롤러를 약간 변경해야합니다.
def schedule_params
params.require(:schedule).permit(:date, :message, :user_id, workers_attributes: [:id, :name, :phone, :_destroy])
end
그런 다음을 사용 @schedule.update_attributes(schedule_params)
하여 일정과 작업자를 업데이트합니다.
최종 JSON은 다음과 같아야합니다.
{
"schedule": {
"date": "...your date",
"message": "...message",
"user_id": "...user_id",
"workers_attributes": [{
"id": 123,
"name: "...name",
"phone": "...phone"
}]
}
}
일정과 관련된 작업자를 추가 / 업데이트 / 삭제할지 여부를 정의하는 작업자 속성 배열을 전달할 수 있습니다. 계속하기 전에 accepts_nested_attributes_for 에 대해 자세히 읽어 볼 수 있습니다 .
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다