Rails 提取包含数据的每个属性

Rails pulling every attribute of included data

我有一个 conversations 控制器,用于为 seller 类型的用户提取所有对话。

卖家可以有 products 可以 purchasedbuyersproduct 可能是免费的。对于对话列表,每个 buyer 都被标记为 clientlead,具体取决于以下因素:

buyer 购买了付费产品或订阅了产品 => client

else => lead

我的converastions_controller是:

@conversation = Conversation.includes(:messages)
                            .get_coach_conversations(@seller)

我的 Conversation 模型有方法:

def self.get_seller_conversations(seller)
  @conversations = seller.conversations
                         .includes(buyer: [:purchases, :user])
                         .joins(:messages)
                         .where(messages: {only_for_buyer: false})
                         .distinct
  new.sorted_conversations(@conversations)
end

def sorted_conversations(conversations)
  conversations.sort_by { |c| c.messages.last.created_at }
               .reverse
end

然后在我的 jbuilder 中为 seller/conversations index 方法我有以下检查来检查 buyerclient 还是lead

coach/conversations/index.json.jbuilder:

json.array!(@conversations.map do |c|
  ...
  ...
  already_client: c.buyer.purchases
                         .where(seller: @seller)
                         .where('subscription = ? OR product_price > ?',
                                 true, 0)
                         .exists?
end)

我认为我可以预期这是一个缓慢的请求,因为我正在提取大量内容进行检查,但是 join 似乎提取了每个 model 的所有属性包含在 ActiveRecord 请求中。想知道是否有更好的方法来检查这个而不需要提取所有数据。

对于我的包含模型,已包含以下信息:

buyer -> users 通过 buyer/seller 模型

连接到 conversations

purchases -> 检查 buyer 是否是 client/lead

user -> buyers namedisplay picture

无论你做什么,你都应该将其移出视图并移至买方的方法中。但据我们所知,如果它只是一个活动记录关系,则不必构建 ruby 对象。在 buyer 上创建范围并传入 @seller

c.buyer.purchases
       .where(seller: @seller)
       .where('subscription = ? OR product_price > ?',true, 0)
       .exists?

转到模型,可能是购买?

class Purchase
  scope :already_client, -> (seller) {
    .where(seller: seller)
    .where('subscription = ? OR product_price > ?',true, 0)
    .exists?
  }
end

在您的 json 生成器中:

already_client: c.buyer.purchases.already_client(@seller)