通过 rails API 调用添加多条记录

Adding multiple records through rails API call

我有一个 Availability 模型,我想发送 API post 请求一次创建多个可用性。

我偶然发现了这个 post on medium 我很兴奋它会解决我的问题但它没有,因为作者在我发送我的时使用了 Rails 表单模板通过 API 请求。

我进一步研究 documentation 找到了创建多个记录的方法,也尝试了那里的方法,但对我没有用。

这是我的控制器代码。 create 方法和 availability_params 方法。

module API
  module V1
    class AvailabilitiesController < ApiController
      def create
        availability = Availability.new(availability_params)
        availability.tutor = current_user

        availability.start_time = DateTime.parse("#{availability_params[:day_of_the_week]} #{availability_params[:start_time]}")
        availability.end_time = DateTime.parse("#{availability_params[:day_of_the_week]} #{availability_params[:end_time]}")

        if availability.start_time < DateTime.current && availability.end_time < DateTime.current
          availability.start_time += 1.week
          availability.end_time += 1.week
        end

        if availability.save
          render json: {
            availability: availability,
            message: 'Your availability was created successfully.'
          }
        else
          render json: { message: 'There was a problem creating your availability.', errors: availability.errors }, status: :bad_request
        end
      end

      def destroy
        Availability.where(id: params[:ids]).destroy_all
      end


      def availability_params
        params.require(:availability).permit(:day_of_the_week, :start_time, :end_time).tap do |availability_params|
          availability_params.require([:day_of_the_week, :start_time, :end_time])
        end
      end

    end
  end
end

前端使用axios的请求是这样的:

axios.post('/api/v1/availabilities', { availability: payload })

销毁函数也发送这种类型的请求:

axios.delete('/api/v1/availabilities', { params: { ids: payload } })

该请求的示例输出,发送时如下所示:

web_1        | Started POST "/api/v1/availabilities" for 172.18.0.1 at 2018-10-29 18:07:27 +0000
web_1        | Cannot render console from 172.18.0.1! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
web_1        | Processing by API::V1::AvailabilitiesController#create as JSON
web_1        |   Parameters: {"availability"=>[{"start_time"=>"2018-10-30T13:00:00.000Z", "end_time"=>"2018-10-30T13:30:00.000Z", "day_of_the_week"=>"Tuesday", "tutor_id"=>1}, {"start_time"=>"2018-10-30T13:30:00.000Z", "end_time"=>"2018-10-30T14:00:00.000Z", "day_of_the_week"=>"Tuesday", "tutor_id"=>1}, {"start_time"=>"2018-10-30T14:00:00.000Z", "end_time"=>"2018-10-30T14:30:00.000Z", "day_of_the_week"=>"Tuesday", "tutor_id"=>1}, {"start_time"=>"2018-10-30T14:30:00.000Z", "end_time"=>"2018-10-30T15:00:00.000Z", "day_of_the_week"=>"Tuesday", "tutor_id"=>1}, {"start_time"=>"2018-10-30T15:00:00.000Z", "end_time"=>"2018-10-30T15:30:00.000Z", "day_of_the_week"=>"Tuesday", "tutor_id"=>1}]}
web_1        |   User Load (1.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" =  ORDER BY id LIMIT   [["id", 1], ["LIMIT", 1]]
web_1        |   ↳ app/controllers/application_controller.rb:114
web_1        | Completed 500 Internal Server Error in 35ms (ActiveRecord: 1.0ms)
web_1        | 
web_1        | 
web_1        |   
web_1        | NoMethodError (undefined method `permit' for #<Array:0x00007f1f26d889d8>):

我到底做错了什么?任何建议将不胜感激谢谢。

你很接近。如果您查看日志,您会发现 params[:availability] 是一个数组,但是您的 create 方法将其处理为表示一项的属性的简单散列。

像这样循环:

 def create
    params[:availability].each { |availability_params|
     availability = Availability.find_or_create_by(availability_params[:id]).update_attributes(availability_params]
  }
  # etc
  end