【问题标题】:Failing to Make a Validation未能进行验证
【发布时间】:2015-12-05 03:41:22
【问题描述】:

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

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

预订控制器

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

抱歉,我是新来的,欢迎提供 wiki 链接。 提前谢谢你。

【问题讨论】:

    标签: ruby-on-rails validation


    【解决方案1】:

    在您的代码中

    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?
    

    【讨论】:

    • NoMethodError in BookingsController#create undefined method `room_detail' in bookingscontroller 我错过了什么吗?
    • 在您的Booking 模型中,您只有room_id 列,但没有room_detail。你必须匹配它。
    • 匹配你的意思是 rails g migration AddRoomDetailToBookings room_detail ??
    • 是的,如果您的模型中同时需要 room_idroom_detail 列。
    猜你喜欢
    • 2021-11-18
    • 2016-01-31
    • 1970-01-01
    • 2015-09-23
    • 2011-11-03
    • 1970-01-01
    • 2014-01-12
    • 2013-10-29
    • 2021-07-29
    相关资源
    最近更新 更多