【发布时间】: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