未能进行验证

时间:2015-12-05 03:41:23

标签: ruby-on-rails validation

对不起,如果我的英语不是最好的。

rails c

>> Booking
=> Booking(id: integer, booking_date: date, start_time: time, end_time: time, created_at: datetime, updated_at: datetime, user_id: integer, room_id: integer, holiday_id: integer)

如果在特定日期和时间已经为特定房间预订,我希望不进行预订。

我试过了 -

def uniqueness_of_booking
    if(booking_date && start_time && end_time && room_detail)
    errors.add(:booking, "is not available") unless Booking.where("? >= start_time AND ? <= end_time AND ?== booking_date AND ?==room_detail",
     start_time, end_time ,booking_date , room_detail)

  end
end

Bookingscontroller

def create
    @booking = current_user.bookings.build(booking_params)
    @booking.user_id=current_user.id
    respond_to do |format|
      if @booking.save
        format.html { redirect_to @booking, notice: 'Booking was successfully created.' }
        format.json { render :show, status: :created, location: @booking }
      else
        format.html { render :new }
        format.json { render json: @new_bookings.errors, status: :unprocessable_entity }
      end
    end
  end

抱歉,我是新来的,欢迎链接到维基。 提前谢谢。

1 个答案:

答案 0 :(得分:0)

在您的代码中

errors.add(:booking, "is not available") unless Booking.where("? >= start_time AND ? <= end_time AND ?== booking_date AND ?==room_detail", start_time, end_time ,booking_date , room_detail)

将返回ActiveRecord的数组。即使它是一个空数组,布尔值也将是true。因此,您可能需要使用

errors.add(:booking, "is not available") unless Booking.where("? >= start_time AND ? <= end_time AND ?== booking_date AND ?==room_detail", start_time, end_time ,booking_date , room_detail).blank?