0

我的朋友帮我做了一些清理工作——但它看起来不像 Rails 的主动记录方式。

首先我是这样写的:

@count_users_approved = current_agent.users.map { |u| u.orders.where("created_at >= ? AND order_status_id = ?", DateTime.now.beginning_of_day, "3")}.count

# 而不是计算记录,结果以这种方式显示:[0,0,1]

我的朋友通过这样写来修复它:

@count_users_approved = Order.where("created_at >= ? AND user_id IN (?) AND order_status_id = ?", DateTime.now.beginning_of_day, current_agent.users.map(&:id), 2).count

我们能写出这么干净的 ActiveRocord 类型吗?

我的模型就是这样设计的。

class Agent < ActiveRecord::Base
  has_many :users
end

class User < ActiveRecord::Base
  belongs_to :agent
  has_many :orders
  has_many :support_histories
  has_one :card_info
end

class Order < ActiveRecord::Base
  belongs_to :user
  belongs_to :order_type
  belongs_to :order_status
end
4

1 回答 1

1

我会这样:

@count_users_approved = Order.joins(:user).where("orders.created_at >= ?", DateTime.now.beginning_of_day).where(users: {agent_id: current_agent.id}, order_status_id: 2).count

您正在加入用户表以测试用户是否已分配给当前代理。

也不需要映射 id,您可以只传递current_agent.users数组,Rails 在构建查询时为您提取对象的 id。

于 2012-10-22T12:07:50.823 回答