我能够使用下面的创建方法一次创建多个记录:
def create
rate_price = params[:rate][:rate]
mlos = params[:rate][:mlos]
start_date = Date.parse(params[:start_date])
end_date = Date.parse(params[:end_date])
dates = (start_date..end_date).to_a.select {|k| (params[:rate][:days]).reject(&:blank?).map(&:to_i).include?(k.wday)}
room_ids = params[:rate][:room_ids].reject(&:blank?).map(&:to_i)
@rates = []
dates.zip(room_ids).each do |date, room_id|
rate = Rate.new(:rate => rate_price, :mlos => mlos, :room_id => room_id, :dayrate => date )
#rate = Rate.find_or_create_by_dayrate(date, :rate => rate_price, :mlos => mlos, :room_id => room_id)
@rates << rate
end
@rates.map(&:save)
respond_to do |format|
if @rates.any? { |rate| !rate.persisted? }
format.html { render action: "new" }
format.json { render json: @rates.detect { |rate| !rate.persisted? }.errors, status: :unprocessable_entity }
else
format.html { redirect_to :back, notice: 'Rates were successfully created.' }
format.json { render json: @rates, status: :created, location: @rates }
end
end
end
但是当我想使用find_or_create_by
(我的代码中的注释行)创建或更新记录(如果它们已经存在)时,似乎没有更新记录,只有创建有效。知道我缺少什么吗?