[英]Ruby on Rails, model method in where
I have a model room with has certain reservations for certain days. 我有一间样板房,某些天有一定的预订。 I have a method that returns if there are any reservations for a certain period.
我有一个方法可以返回,如果在一定时期内有任何保留。 How can I get all the rooms without reservations for that period?
在那个时期我该如何预订所有没有预订的房间?
This is the code I have now, but when I use 这是我现在拥有的代码,但是当我使用
@rooms = @category.rooms.availible(@date_start, @date_end),
It returns all the rooms no matter what relations. 无论什么关系,它都会返回所有房间。 And when I use
当我使用
room.reservations.where("date_start >= ? || date_end <= ?", startd, endd).count
It returns the amount just fine -.- 它返回的金额就很好-.-
class Room < ActiveRecord::Base
attr_accessible :cat_id, :room_nr
validates_uniqueness_of :room_nr
has_many :reservations
belongs_to :category, foreign_key: "cat_id"
def self.availible(startd, endd)
where(self.Resvs(startd, endd)==0)
end
def self.Resvs(startd, endd)
return joins(:reservations).where("date_start >= ? || date_end <= ?", startd, endd).count
end
end
I moved the query to the controller for now, to get he rooms i use 我现在将查询移至控制器,以获取我使用的房间
@rooms = @category.rooms.joins('LEFT OUTER JOIN reservations ON reservations.room_id = rooms.id').where("date_start >= ? || date_end <= ?", @date_start, @date_end)
But that returns all the rooms that have a reservation, no matter what date (also the rooms need to come from their parent @category) 但这会返回所有预订的房间,无论日期如何(房间也必须来自其父@category)
Getting close, changed it select the ones where reservation is off like this 越来越近,改变了它,选择了这样的预订关闭的
@rooms = @category.rooms.joins('LEFT OUTER JOIN reservations ON reservations.room_id = rooms.id').
where("room_id IS NULL OR date_start > ? OR date_end < ?", @date_end, @date_start)
Works with one reservation but when i add more reservations on one room is doesn't work anymore 仅可用于一项预订,但是当我在一个房间中添加更多预订时,将无法再使用
In this case you can use NOT EXISTS
like this : 在这种情况下,您可以像这样使用
NOT EXISTS
:
def self.availible(startd, endd)
@category.rooms.where("NOT EXISTS(select 1 from reservations where reservations.room_id = rooms.id and (date_start > ? OR date_end < ?))", startd, endd)
end
Hope this helps 希望这可以帮助
Fixed it! 修复! Thx for the help
谢谢你的帮助
def self.availible(startd, endd)
where("NOT EXISTS(select 1 from reservations where reservations.room_id = rooms.id and ((date_start>=:date_start AND date_start<=:date_end) OR (date_end>=:date_start AND date_end<=:date_end)))", {date_start: startd, date_end: endd})
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.