2017-05-31 88 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

相关问题