【问题标题】:How to do POST request of two associated Rails models from React?如何从 React 对两个关联的 Rails 模型进行 POST 请求?
【发布时间】:2017-05-05 00:26:44
【问题描述】:

我有一个用作后端的 rails-api 应用程序和用作前端的 react 应用程序。

在 Rails 内部,我有一个 Schedule 模型 has_many workersWorker 模型 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


    【解决方案1】:

    我的朋友昨晚给了我一个提示,我得到了它的工作。他说没有办法获得 schedule_id 信息,除非我提交它,被接受,并返回一个新的 schedule_id 是什么的响应。

    所以为了解决我的问题,我不得不提出两个请求。首先,我需要在 rails 中请求调度模型,等待 rails 接受它,并等待 rails 返回response。响应内部是 schedule_id。我 .then 分配 schedule_id 与我从 rails 获得的时间表 ID。

    有点乱,我需要清理一下。但这对我有用:

    Client.postSchedule(this.state.date, (schedule) => {
      this.setState({schedules: this.state.schedules.concat([schedule])})
    }).then(() => Client.postWorker(this.state.worker, this.state.phone, this.state.schedules[this.state.schedules.length - 1].id, (worker) => {
        this.setState({workers: this.state.workers.concat([worker])})
      })
    )
    

    this.state.schedules[this.state.schedules.length - 1].id 行有点模糊。它真正的作用是,我有一系列日程表来存储我的日程表对象。我只是让 React 知道获取数组中的最后一个调度(这将是最新的调度),并给我调度数组中最后一个调度对象的 ID。

    简而言之,(sends request to schedule) -&gt; (wait response back from Rails that contains the schedule_id that I need) -&gt; (use that schedule_id information to send another request)。解决办法是检查then的。

    【讨论】:

      【解决方案2】:

      在这里,您可以在 Schedule 模型中使用 rails accept_nested_attributes_for。

      在您的计划模型中添加以下行

       accepts_nested_attributes_for :workers
      

      然后在您的 SchedulesController 中,更新 schedule_params 方法。

      def schedule_params
      
         params.require(:schedule).permit(:user_id, :date, workers_attributes: [:id, :name, :phone])
      
      end
      

      在你的反应应用中

      function postSchedule(date, cb) {
        return fetch(`api/schedules`, {
         method: 'POST',
         headers: {
          'Content-Type': 'application/json',
         },
         body: JSON.stringify({
          date: date,
          user_id: 1,
          workers_attributes: [
           {
            name: worker_name,
            phone: phone
           }
          ]
      
        })
      
       }).then((response) => response.json())
      
       .then(cb); //cb setStates schedules state in main react app  
      };
      

      现在只有一个请求可以满足您创建调度和工作人员的目的。

      供参考 http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多