使用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.phones
和phone.cart_items
設置正確,和他們工作得很好(的CartItem
cart_item
=實例和Phone
phone
=實例)。
有沒有辦法,我可以使用來自關聯的數據庫查詢來查找電話ID爲x(params)的所有用戶購物車項目(@user.cart.cart_items
)?注意:我需要實際的對象,所以我可以查看電話的字段(即:@user.cart.cart_items.phone.brand_name
。)。
謝謝......只是好奇,你會爲應用程序推薦。迭代現有SQL查詢或單獨的數據庫查詢(實際上是您給出的答案)的'.each'方法? – the12
在大多數情況下,SQL查詢應該更有效率。在這個問題中,where(phone_id:x)'比使用每個循環找到匹配記錄更有效率。 – wesley6j