Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

how do I append something to the columns rails selects rather than overwriting it? Thanks!

like image 826
dansch Avatar asked Jun 07 '26 03:06

dansch


1 Answers

Rails is going to select '*' by default, so that kinda goes against what you're saying about only wanting to select some columns. 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..

@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.

like image 105
radixhound Avatar answered Jun 08 '26 16:06

radixhound