【发布时间】:2017-05-05 00:26:44
【问题描述】:
我有一个用作后端的 rails-api 应用程序和用作前端的 react 应用程序。
在 Rails 内部,我有一个 Schedule 模型 has_many workers 和 Worker 模型 belongs_to schedule。当用户创建新计划时,他们可以选择date 并选择工作人员的name。我的挣扎是,我想不出一种方法来传递工人的schedule_id。
这是我所拥有的:
我有两种获取方法;每个都向指定的 API 发送数据/发出 POST 请求。
function postSchedule(date, cb) {
return fetch(`api/schedules`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
date: date,
user_id: 1
})
}).then((response) => response.json())
.then(cb); //cb setStates schedules state in main react app
};
function postWorker(workerName, cb) {
return fetch('api/workers', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
worker: workerName,
schedule_id: //how do I know schedule_id?
})
}).then((response) => response.json())
.then(cb); //cb setStates workers state in main react app
}
导轨型号:
//schedule.rb
class Schedule < ApplicationRecord
belongs_to :user
has_many :workers
end
//worker.rb
class Worker < ApplicationRecord
belongs_to :schedule, optional: true
end
Rails 控制器:
//schedules_controller.rb
def create
@schedule = Schedule.new(schedule_params)
if @schedule.save
render json: @schedule
else
render json: @schedule, status: :unprocessable_entity
end
end
//workers_controller.rb
def create
@worker = Worker.new(worker_params) #params.permit(:name, :phone, :schedule_id)
if @worker.save
render json: @worker
else
render json: @worker, status: :unprocessable_entity
end
end
表格看起来像这样。用户将同时创建一个新计划和一个新工作人员。
如果用户正在创建一个新的日程表,显然这个日程表在数据库中还没有存在,所以直到提交后我才知道这个日程表的 ID。当我做一个新工人时,它需要 schedule_id。如何让 Rails 知道这个 worker 的 schedule_id 是什么?
将新创建的计划分配给新创建的工作人员的好策略是什么?
【问题讨论】:
标签: ruby-on-rails api reactjs associations