Rails + Vue로 작업하는 프로젝트가 하나 생겼다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Rails from '@rails/ujs' |
위와 같이 임포트 한 뒤에,
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const data = new FormData(); | |
data.append('task[assignee_id]', this.someUserId); | |
data.append('task[name]', this.taskName); |
rails의 ujs는 JSON를 완벽하게 지원하지 않기 때문에 위와 같이 데이터를 준비하고,
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Rails.ajax({ | |
url: `http://SERVER_URL/tasks/${task.id}` | |
type: 'PATCH', | |
data: data, | |
dataType: 'JSON', | |
}); |
이런 방식으로 쏴주면 되는데, 이 때 주의사항이 있다.
assignee_id
는 null일 수도, 어떤 값을 가질 수도 있다. this.someUserId
가 null인 경우, 해당 라우팅을 처리하는 컨트롤러의 메소드에서는 0으로 들어온다. null과 실제 0을 구별하지 못하게 되는 문제가 생기며, 특히 위의 예제처럼 user_id
가 0인 유저가 존재하지 않는 경우에는 FK 제약조건을 위배하여 task가 생성조차 되지 않게된다.
여러 테스트를 해본 결과, rails에서는 빈 문자열 ''
를 nil
로 인식하는 것을 확인했다. ''.to_i
나 'null'.to_i
모두 0을 반환하는데, 신기하게도 빈 문자열은 nil
로 변환해주는 것 (…)
따라서 위 코드를 고치면 다음과 같다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const data = new FormData(); | |
data.append('task[assignee_id]', this.someUserId || ''); | |
data.append('task[name]', this.taskName || ''); |