简体   繁体   English

如何从对象数组中获取属性以在Rails中创建不同的模型?

[英]How to get attributes from array of objects to create different model in Rails?

I have a Rails server running on the background used to capture API requests. 我有一个在后台运行的Rails服务器,用于捕获API请求。 Inside Rails, I have 2 associated models: schedule and worker . 在Rails内部,我有2个关联的模型: scheduleworker schedule has_many workers and worker belongs_to schedule schedule has_many workers and worker belongs_to schedule

I am making a POST request from React (fetch method), this is what it looks like on React: 我正在从React(fetch method)发出POST请求,这就是在React上的样子:

  return fetch(`api/schedules`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      date: date,
      message: message,
      user_id: 1,
      worker_info: {name: workerName, phone: phone}
    })

On Rails schedules_controller: 在Rails schedules_controller上:

  def create
    @schedule = Schedule.new(schedule_params)
    @worker = @schedule.workers.new(worker_params)
    @worker.save
    if @schedule.save
      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.require(:worker_info).permit(:name, :phone)
  end

Note, the codes above works fine 注意,上面的代码可以正常工作

I want to send to api/schedules several parameters: date, message, user_id , and some worker info ( name, phone ). 我想向api/schedules发送几个参数: date, message, user_id和一些工作人员信息( name, phone )。

Schedule itself has attributes date, message, and user_id . Schedule本身具有date, message,user_id属性。 Worker has attributes name and phone . 工人具有namephone属性。 My plan is to make only one request to Rails, stub some worker info, and let Rails create worker object inside Schedule. 我的计划是仅向Rails发出一个请求,对一些工作程序信息进行存根,然后让Rails在Schedule中创建工作程序对象。 Again, I can do that with code above. 同样,我可以使用上面的代码来做到这一点。

My question is, the complexity increases when I try to send, instead of a single object worker_info , an array of worker_infos . 我的问题是,在复杂性增加,而不是一个单一的对象,当我尝试发送, worker_info ,数组worker_infos

worker_info: [{name: workerName, phone: phone}]

(In the future, I want to send a variable amount of workers, that's why I added the array. Right now, I just need to make it work with just one) (将来,我想发送可变数量的worker,这就是为什么我添加数组的原因。现在,我只需要使其与一个数组一起工作即可)

worker_info: [{name: 'Test Worker 1', phone: '12345'}, {name: 'Test Worker 2', phone: '54321'}, ...]

I cannot figure out how to extract worker information to make worker object if I add the array [] . 如果添加数组[]我将无法弄清楚如何提取工作人员信息以使工作人员成为对象。 Here is the rails server error: 这是Rails服务器错误:

Started POST "/api/schedules" for 127.0.0.1 at 2017-05-25 17:19:32 -0700
Processing by SchedulesController#create as */*
  Parameters: {"date"=>"2017-05-27T02:00:00.000Z", "message"=>"Mireya Hiya~!!", "user_id"=>1, "worker_info"=>[{"name"=>"Mireya How
e", "phone"=>"1234567890"}], "schedule"=>{"date"=>"2017-05-27T02:00:00.000Z", "user_id"=>1, "message"=>"Hello test!!"}}
Completed 500 Internal Server Error in 11ms (ActiveRecord: 0.0ms)



NoMethodError (undefined method `permit' for #<Array:0x007f8381fd2530>):

app/controllers/schedules_controller.rb:59:in `worker_params'
app/controllers/schedules_controller.rb:20:in `create'

I am avoiding Rails' accept_nested_attributes_for method because the way my other code is structured, it won't work and has been causing much grief. 我避免使用Rails的accept_nested_attributes_for方法,因为我的其他代码的结构方式无法正常工作,并且引起了很多麻烦。

How can I extract the information inside worker_info: [{name: workerName, phone: phone}] and create new Worker object with that? 如何提取worker_info: [{name: workerName, phone: phone}]worker_info: [{name: workerName, phone: phone}]创建新的Worker对象?

Ho, man. 老兄

First of all, good on 'ya for avoiding accept_nested_attributes_for . 首先,在'ya上避免使用accept_nested_attributes_for What a cluster you-know-what. 您知道什么集群。

So, the whole point of strong parameters is to be able to whitelist stuff when doing mass assignment. 因此, strong parameters的全部要点是能够在进行质量分配时将材料列入白名单。 This doesn't really seem like a mass assignment situation, so I would abandon ship on the whole approach. 这似乎并不是大规模分配的情况,因此我将放弃整个方法。

Instead, I would go bare knuckles codez. 相反,我会赤手空拳。 You know, something like: 您知道,类似:

app/services/api/schedules/workers_service.rb

class Api::Schedules::WorkersService

  class < self

    def call(params={})
      ...
      # do a bunch of clever stuff
      ...
    end

  end
end

And then in SchedulesController , do something like: 然后在SchedulesController ,执行以下操作:

def create
  @schedule = Schedule.new(schedule_params)
  if @schedule.save
    Api::Schedules::WorkersService.call(
      schedule_id: @schedule.id,
      worker_info: params[:worker_info]
    )
    render json: @schedule
  else
    render json: @schedule, status: :unprocessable_entity
  end
end

You probably want to wrap some of that junk in a transaction in case things go South. 您可能希望将一些垃圾包装在事务中,以防万一。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM