2011-03-26 64 views
0

嗨 我想知道是否有辦法做到這一點,而不涉及高級SQL代碼?Ruby On Rails 3,通過兩個值在不同模型中的組合排序

模型1. 產品 :價格的has_many

模型2 零售商 :價格的has_many :HAS_ONE輪廓

型號3. 價格 - 價格:整數 :belongs_to的:零售商 : belongs_to:產品

模型4. 配置文件 - Shippingcost:整數 :belongs_to的:零售商

我希望能夠進行排序(:價格+:shippingCost),我知道如何使用SQL做到這一點,左聯接和創建「(BLA + bla2)AS totalPrice並對其進行排序總價,但有沒有更簡單的方法來做到這一點?

+0

檢查出meta_where gem。 Ernies的目標是通過ruby/rails編程減少/刪除sql代碼的必要性...看看http://metautonomo.us/projects/metawhere/並嘗試他的助手,看看你是否可以在沒有sql的情況下完成它-碼。如果你需要一個非左連接,你可能最終不得不「xxxx」加上xxxx作爲一個純sql片段來定義正確的連接表 – Ingo 2011-03-26 20:34:17

回答

0

所以,就像那樣。但它嵌套得太深

Product.includes(:prices => {:retailer => :profile}).select("products.*, (prices.price + profiles.shippingcost) AS sum).order(:sum) 
+0

嗨fl00r, 我管理做這個。 @price = Price.joins(:零售商,零售商=>:個人資料) 日誌sais。 SELECT'prices'。* FROM'prices' INNER JOIN' retailers' ON'retailers'.'''''prices'.'retailer_id' INNER JOIN' profiles' ON'' profiles'.'retailer_id' ='retailers' .'id' 但它缺少AS和ORDER BY ...下面的最終代碼顯示它應該如何看 SELECT('prices'.price +'profiles'.shippingCost)AS totalPrice FROM'prices' INNER JOIN '零售商'ON'零售商'.'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''訂單總價 – Philip 2011-03-27 09:51:27

+0

解決方案: @ price:price.select(''prices'。*,('prices'.price +'profiles'.shippingCost)AS totalPrice')。joins(:retailer,:retailer => profile).order(:totalPrice)。全部 我現在的問題是,當我嘗試使用XML和JSON時,我得到一個零例外...... – Philip 2011-03-27 10:21:28

相關問題