【问题标题】:Save an array of ActiveRecords objects保存一组 ActiveRecords 对象
【发布时间】:2016-10-21 03:13:36
【问题描述】:

我试图在我的控制器中保存一个 ActiveRecords 数组,但出现了这个错误:

#<Array:...> 的未定义方法“保存”

我有这个模型的方法:

def self.import(file)
  reservations = []
  CSV.foreach(file, headers: true ) do |row|
    room_id = Classroom.where(code: row[0]).pluck(:id).first
    row[0] = room_id
    reservations << Reservation.new(number_of_guests: row[1], check_in_date: row[2], check_out_date: row[3], room_id: row[0])
  end
  reservations
end

我有以下控制器:

def create_import
  @reservations = Reservation.import(params[:file].path)
  respond_to do |format|
    if @reservations.save
      format.html { redirect_to @reservation, notice: 'Reservations was successfully created.' }
      format.json { render :show, status: :created, location: @reservation }
    else
      format.html { render :import }
      format.json { render json: @reservations.errors, status: :unprocessable_entity }
    end
  end
end

我该如何做这种保存方法?我想在我的视图中显示包含错误的报告。

【问题讨论】:

  • 应该Classroom.where(code: row[0]).pluck(:id)Classroom.where(code: row[0]).pluck(:id).first???第一个会给你 room_id 包装在一个数组中。
  • @br3nt 是的,已修复。谢谢

标签: ruby-on-rails arrays ruby activerecord rails-activerecord


【解决方案1】:

好吧,你应该对它们每个都调用save方法:

@reservations.each(&:save)

或者安装一些提供多个insert 功能的第三方gem。您还应该重写您的if 语句,因为上面的表达式将始终返回集合本身,因此评估为true

【讨论】:

  • 那么如果我使用这种方法,我怎样才能将所有的错误返回到我的视图中呢?
  • @gumaro:您可以使用rejectselect代替each收集保存失败或成功的实例。
  • records_with_errors = @reservations.reject {|r| r.save }
  • 这一切都在create_import 操作中。因此,成功导入所有预订的成功条件是没有错误记录。当reservations_with_errors.empty? 返回true 时,就会发生这种情况。如果要检查是否有错误,可以改用reservations_with_errors.any?
  • @gumaro: 那么你可以使用partition 方法而不是select/reject,这应该给你的两个集合,一个已经进入数据库,一个已经save 方法失败。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-06
  • 1970-01-01
  • 2016-01-23
  • 2021-04-24
  • 2016-02-21
相关资源
最近更新 更多