0

我能够使用下面的创建方法一次创建多个记录:

  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(我的代码中的注释行)创建或更新记录(如果它们已经存在)时,似乎没有更新记录,只有创建有效。知道我缺少什么吗?

4

1 回答 1

1

调用该方法时,find_or_create_by仅在您要创建新记录时使用。根据我对您的代码的理解,您想使用dayrate日期列来创建费率。而且由于您的问题是为什么不更新记录,所以我假设您想要更新记录(如果它们已经在数据库中)。您可以使用以下代码实现这一点

rate = Rate.where(dayrate: date).first_or_initialize
rate.attributes = { rate: rate_price, mlos: mlos, room_id: room_id }

this will make sure that the rate's attributes will use the values you pass if they pass the validation (since you're calling map(&:save) after the block.

于 2013-03-19T15:47:56.207 回答