【问题标题】:Query a has many model, after querying the belongs to model查询一个有很多模型,在查询属于模型之后
【发布时间】:2014-06-20 06:30:10
【问题描述】:

我有两个模型 User 和 Product 和一个用户 has_many :products。 给定一组用户,我如何找到他们创建的产品。

问题:查找在特定地址附近可销售和正在销售的所有产品。所以我首先找到住在附近的所有用户。然后查询这些用户销售的所有产品。然后检查这些产品的可用性。但它不起作用。为什么会这样?

在我的控制器索引操作中,我有:

@users = User.near(params[:nearby], 20)
@users.find_each do |user|
  @products << user.products_selling # <-- Does not work
end
@products = @products.available

product.rb型号

belongs_to :seller, class_name: 'User', foreign_key: :user_id, dependent: :delete
scope :available, -> { where(availableforsale: true) }

user.rb型号

has_many :products_selling,  class_name: 'Product'

错误是

undefined method `<<' for nil:NilClass

请注意 - 如果我将 &lt;&lt; 更改为 = 则它可以工作,但仅查询最后一个用户的产品而不是所有用户(显然)。

请帮忙

【问题讨论】:

  • 什么是错误和型号?这段代码小到明白问题所在。
  • 向问题添加更多信息
  • 在循环上方定义@products
  • @zishe,问题已更新。
  • @GB,我现在得到 undefined method available' 的 #<0x0000010d5e27f8>

标签: ruby-on-rails ruby ruby-on-rails-4


【解决方案1】:
@users = User.near(params[:nearby], 20)

@products = Product.where(["user_id IN (?)", @users.map(&:id)]).available

在下面修复您的代码,(但在循环内查询不是一个好主意)

@products = [] # initialize empty array before you insert into it
@users.each do |user|
  @products << user.products_selling.to_a # To insert array of products rather than a Relation
  # Now @products is an Array of Arrays.
end
@products = @products.flatten.select(&:availableforsale) # Flatten the Array, and select only the ones availableForSale

【讨论】:

  • @Amey,我已经为您的代码添加了修复程序(应该可以工作,希望如此)。但它有一个N+1 问题。即如果@users 的计数为100,则查询的总数将为101。我的第一个解决方案将只进行2 个查询,无论@users 的计数是多少
  • 是的,您的第一个解决方案看起来也更干净。这是显而易见的选择。再次感谢。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多