2011-03-10 102 views
0

我有一個模型Xbelongs_to :y並具有現場quantityRails 3中ActiveRecord的查詢問題

Y模型:

has_many :xs 
belongs_to :user 
belongs_to :z 

User模型:

has_many :ys 
has_many :xs, :through => :ys 

Z模型

has_many :ys 
has_many :users, :through => :ys 

我怎麼找到有多少xs用戶有特定的z? 如何找到用戶對特定zxs的數量字段的總和?

我想找到一個解決方案,它使用rails 3的活動記錄查詢語法,並儘可能在數據庫級別進行。我會很感激任何幫助。

+6

x,y和z不是有用的名稱。請使用真實的值而不是假的值。我們不會竊取你的想法。它也可以讓我們用你的話說話。 –

+0

__User__'has_many:zs,:through =>:ys'? – fl00r

回答

0

讓我試着用另一種方式來翻譯這個。

的X車型成爲車項目

class CartItem 
    belongs_to :cart 
    attr_accessor :quantity 
end 

的Y型變成了車

class Cart 
    has_many :cart_items 
    belongs_to :user 
    belongs_to :section 
end 

用戶模式保持不變

class User 
    has_many :carts 
    has_many :cart_items, :through => :carts 
end 

的Z型成爲科

class Section 
    has_many :carts 
    has_many :users, :through => :carts 
end 

因此,你問:

  • 我怎樣才能找到一個用戶有多少車中的商品有特定的部分?
  • 我怎樣才能找到一個用戶具有 特定部分的購物車項目的數量字段的總和?

以下範圍添加到CartItem

scope :for_section, lambda { |section| 
    includes(:cart).where('carts.section_id = ?', section.id) 
} 

而且答案會

  • user.cart_items.for_section(部分).Count之間
  • user.cart_items.for_section(節).sum('quantity')

這些命令將生成確切的SQL查詢來查找您正在查找的答案!