2013-03-01 44 views
0

我不是如何從Rails中不同的模型中查詢模型的數據完全清楚內的一個模型。這些模型具有has_many & belongs_to關係。這兩款車型分別是「Gear」和「line_item」。 齒輪的has_many line_items和的LineItem belongs_to的齒輪。導軌 - 查詢從一個不同的模型用的has_many和belongs_to的關係

我想要做的是查詢數據庫中屬於具有NULL或空白cart_id(這是其中一個字段)的Gear對象的所有line_items,然後計算它的可用性。因爲在這種情況下,齒輪是在特定日期和時間存儲在一個LINE_ITEM(日期,結束日期,START_HOUR,END_HOUR)..將不會在Ruby中我GOOGLE做了很多先進的quering周圍租出去了,現在我不知道我應該如何使用

可枚舉的齒輪式模型是這樣的:

line_items.inject(0) {|line_item| line_item.where('line_items.cart_id' => NULL } 

或者,如果我可以用這樣的齒輪模型一個範圍:

scope :availablegear, lambda { includes(:line_items).where('line_items.cart_id' => nil) } 

我知道兩者的語法可能都不正確,所以我可以對使用方法和使用方法進行一些指導。

謝謝。

我的項目是使用Rails 3.2.0,1.9.4紅寶石MySQL的&

編輯與建議現在答案

class Gear < ActiveRecord::Base 
    attr_accessible :title, :size, :price, :sub_category_id, :user_id, :image, :image_a, :image_b, :image_c, :image_d, :image_e, :image_f, :image_g, :image_h, :image_i, :remote_image_url, :color, :year, :latefee, :cancellation, :minrental, :policy, :about, :address, :city, :state, :zip, :country, :latitude, :longitude, :gmaps 
    ...some code omitted for brevity 
    has_many :line_items 
    scope :availablegear, joins(:line_items).where(:line_items => {:cart_id => nil}) 
    ...some code omitted for brevity 

end 

,當我啓動了Rails的控制檯,我做AG = Gear.find( 4),然後就g.availablegear我收到以下錯誤:NoMethodError:未定義的方法`availablegear」爲#

+0

你想回來的結果是什麼?齒輪或訂單項? – 2013-03-01 14:13:02

+0

我試圖讓訂單項返回 – DaveG 2013-03-01 17:35:37

回答

2

如果你正在試圖獲得行項背:

class Gear < ActiveRecord::Base 
    has_many :line_items 
end 

class LineItem < ActiveRecord::Base 
    belongs_to :gear 

    scope :available, where(:cart_id => nil) 
end 

然後,如果你有一個齒輪,你可以調用

gear.line_items.available 

這將返回屬於gear,並且有一個項目沒有cart_id

+0

工作。謝謝。 – DaveG 2013-03-02 13:14:02

4

我認爲你正在尋找的查詢

Gear.joins(:line_items).where(:line_items => {:cart_id => nil}) 

你可以把它放在一個範圍在Gear類:

class Gear< ActiveRecord::Base 
    scope :available, joins(:line_items).where(:line_items => {:cart_id => nil}) 
end 

你可以找到一些Rails Query Guide更多的幫助(見11.3與條件加盟)。

+0

當我打電話給示波器時,我不是在做一些像Gear.find(4).available? ....現在,我在Rails控制檯中收到一個未定義的方法錯誤。我正在更新我的代碼 – DaveG 2013-03-01 17:34:55

+0

@DaveG你就像這個'齒輪。可用「,並且您將獲得包含至少一個line_items且沒有cart_id的所有齒輪的關係。 – Baldrick 2013-03-01 17:58:38

相關問題