Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/54.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 复杂的查找条件以返回一条记录_Ruby On Rails - Fatal编程技术网

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