簡體   English   中英

Rails,添加列以選擇語句

[英]Rails, add column to select statement

@products=@products
  .group('products.id')
  .joins(:inventories)
  .select('products.*, sum(inventories.units_available) as `level`')

是我可以選擇的東西,盡管我不想使用產品。*因為我不想每次都獲取所有數據,所以我只想將sum()添加到Select {stuff}中的內容中制品

如何將某些內容添加到rails選擇的列而不是覆蓋它? 謝謝!

Rails默認情況下將選擇“ *”,因此有點違反您只想選擇一些列的說法。 您是否嘗試過僅處理所需的列,然后根據需要選擇獲取更多/所有列? 我假設您需要product_id才能使連接正常工作。

@products = @products
  .group('products.id')
  .joins(:inventories)
  .select('products.id, inventories.product_id, inventories.units_available, sum(inventories.units_available) as `level`')

if i_need_some_other_column
  @products = @products.select('products.some_other_column') 
end

if i_really_need_all_the_columns
  @products = @products.select('products.*, inventories.*')
end

我99%確信,鏈接選擇將智能添加其余的列。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM