2017-05-31 95 views
0

使用Rails 5.0:如何通過與ActiveRecord查詢關聯獲取對象?

class User < ApplicationRecord 
    belongs_to :cart, {:optional => true} 
end 

class Phone < ApplicationRecord 
    has_many :cart_items 
end 

class CartItem < ApplicationRecord 
    belongs_to :cart, {:optional => true} #has cart_id as column 
    belongs_to :phone, {:optional => true} #has phone_id as column 
end 

class Cart < ApplicationRecord 
    has_one :user 
    has_many :cart_items 
end 

我的應用程序的工作原理如下。有用戶(User),有購物車(Cart),並在這些購物車中有購物車項目(CartItem)。在每個購物車項目中都有關於購物車的信息,包括購買哪些電話(Phone)。

我目前使用.each循環來循環user.cart.cart_items,如果它返回一個購物車項目有params[:phone_id],那麼它會更新它並從循環中斷開。

user_items = @user.cart.cart_items 
if user_items.any?{|x| x.phone_id == params[:phone_id].to_i} 

    user_items.each do |x| 
    if x.phone_id == params[:phone_id].to_i 
    x.update_attributes(:quantity_sold => params[:quantity].to_i) 
    break 
    end 
    end 

雖然它的作品,我想知道是否有使用數據庫查詢來查找與user_items(@user.cart.cart_items)相關的所有相關電話的方式。注:@user就是當前用戶登錄

我試着用@user.cart.cart_items.where(:phone_id => 1),和它的工作,而是試圖通過查詢@user.cart.cart_items.where(:phone_id => 1).phone從那裏取回手機時,返回的錯誤undefined method 'phone' for #<CartItem::ActiveRecord_AssociationRelation:0x007fa38a461128>

我檢查,看看我的協會是否通過(cart_item.phonesphone.cart_items設置正確,和他們工作得很好(的CartItemcart_item =實例和Phonephone =實例)。

有沒有辦法,我可以使用來自關聯的數據庫查詢來查找電話ID爲x(params)的所有用戶購物車項目(@user.cart.cart_items)?注意:我需要實際的對象,所以我可以查看電話的字段(即:@user.cart.cart_items.phone.brand_name。)。

回答

2

這給了你相關的CartItems:

user_items_with_matching_phone = @user.cart.cart_items.where(phone_id: x) 

爲了得到第一個項目的電話:

user_items_with_matching_phone.first.phone 

要更新的第一個項目(你在每個循環做基本上是什麼):

user_items_with_matching_phone.first.update_attributes(quantity_sold: params[:quantity].to_i) 

但是,你不能這樣做user_items_with_matching_phone.phone因爲user_items_with_matching_phone比單個對象更類似於數組。你可以得到的長度,如果通過user_items_with_matching_phone.size

+0

謝謝......只是好奇,你會爲應用程序推薦。迭代現有SQL查詢或單獨的數據庫查詢(實際上是您給出的答案)的'.each'方法? – the12

+0

在大多數情況下,SQL查詢應該更有效率。在這個問題中,where(phone_id:x)'比使用每個循環找到匹配記錄更有效率。 – wesley6j

相關問題