Ruby on rails 复杂的查找条件以返回一条记录
我正在查询我的预订模式以获取详细信息,包括有许多约会的列表 为此,我使用了一个范围:Ruby on rails 复杂的查找条件以返回一条记录,ruby-on-rails,Ruby On Rails,我正在查询我的预订模式以获取详细信息,包括有许多约会的列表 为此,我使用了一个范围: scope :current_cart, Booking.includes(:appointments).where(:parent_id => 1).where(:complete =>nil).order("created_at DESC").limit(1) 然后在视图中: <% @booking.appointments.each do |appointment| %>
scope :current_cart,
Booking.includes(:appointments).where(:parent_id => 1).where(:complete =>nil).order("created_at DESC").limit(1)
然后在视图中:
<% @booking.appointments.each do |appointment| %>
# info output
<% end %>
这是我担心的[0]点。我想我正在使用一个想要返回集合的方法,这意味着我必须声明我想要第一条(唯一的)记录。如何声明更适合获取成员的类似范围 尝试将“.first”钉在作用域的末尾。作用域只是常规的AREL查询,因此您可以像平常一样使用任何标准方法。向作用域中添加。第一个或[0]会产生错误:
undefined method `default_scoped?' for
谷歌搜索给出了这个:显然,添加.first或[0]会停止它的可链接性,因此它会给出一个错误。用这个答案,我做到了:
scope :open_carts,
Booking.includes(:appointments).where(:parent_id => 1)
.where(:complete =>nil).order("created_at DESC")
def self.current_cart
open_carts.first
end
有点凌乱,但我更喜欢我的模型中的凌乱,而且看起来也不是荒谬的
scope :open_carts,
Booking.includes(:appointments).where(:parent_id => 1)
.where(:complete =>nil).order("created_at DESC")
def self.current_cart
open_carts.first
end