2013-01-03 35 views
0

我在查詢我的預訂模型以獲取詳細信息,其中包括has_many約會列表。複雜查找條件以返回一條記錄

要做到這一點我使用範圍:

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 %> 

得到這個工作,在控制器中,我必須這樣做:

@booking = Booking.current_cart[0] 

這是我擔心的[0]位。我想我正在使用一個想要返回一個集合的方法,這意味着我必須聲明我想要第一個(唯一)記錄。我如何陳述一個更適合於獲取成員的類似範圍?

回答

0

添加。首先或[0]的範圍給出錯誤:這給了這個

undefined method `default_scoped?' for 

谷歌搜索:
undefined method `default_scoped?' while accessing scope

因此很明顯,添加。首先或[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 

點點亂,但我寧願在我的模型一團糟,這不是睜眼說瞎話來看待。

1

嘗試將「.first」添加到範圍的末尾。範圍只是普通的AREL查詢,因此您可以像平常一樣使用任何標準方法。

+0

這推動我回答謝謝! – Will