简体   繁体   English

Rails,添加列以选择语句

[英]Rails, add column to select statement

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

is something I have that works to select, though I don't want to use products.* because I don't want ALL the data everytime, I just want to add the sum() to the stuff in the Select {stuff} from products 是我可以选择的东西,尽管我不想使用产品。*因为我不想每次都获取所有数据,所以我只想将sum()添加到Select {stuff}中的内容中制品

how do I append something to the columns rails selects rather than overwriting it? 如何将某些内容添加到rails选择的列而不是覆盖它? Thanks! 谢谢!

Rails is going to select '*' by default, so that kinda goes against what you're saying about only wanting to select some columns. Rails默认情况下将选择“ *”,因此有点违反您只想选择一些列的说法。 Have you tried doing only the columns you need and then optionally getting more / all the columns if you need them? 您是否尝试过仅处理所需的列,然后根据需要选择获取更多/所有列? I'm assuming you need product_id for the join to work.. 我假设您需要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

I'm 99% sure that chaining the select will intelligently add the rest of the columns. 我99%确信,链接选择将智能添加其余的列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM