0

I have a query with multiple JOINs.

At the moment I get a result with all the columns from all the tables. And some of the columns have identical names because that's how it's in my database. How can I select the columns to return and adjust their names in the result set?

I've tried:

    result = MyModel1.join(:table2, id: :table2_id)


    if condition1
      result = result.join(.....).where(.....)
    end


    if condition2
      result = result.join(.....).where(.....)
    end

    # and so on....


    result

And if I'm doing this:

  result.select([Sequel[:model1][:column1], Sequel[:model2][:column2]])

I end up with this after I convert it to json:

  [{"row":["column1_value1","column1_value11"]},{"row":["column1_value2","column1_value22"]},{"row":["column1_value3","column1_value33"]}]

What's the "row"? How to get rid of it? How to add the names of the columns and change the structure of that json response so it looks proper?

I want something like this:

  [
    {"column1": "column1_value1", "column2" "column1_value11"},
    {"column1": "column1_value2", "column2" "column1_value22"},
    {"column1": "column1_value3", "column2" "column1_value33"}
  ]
Ojman
  • 51
  • 4

2 Answers2

0

If the outcome is relatively small you might deal with the output.

outcome =
  [{"row":["column1_value1","column1_value11"]},
   {"row":["column1_value2","column1_value22"]},
   {"row":["column1_value3","column1_value33"]}]

outcome.
  map(&:values).                 # get rid of "row"
  map(&:flatten).                # get rid of nesting
  map(&%i|c1 c2|.method(:zip)).  # attach titles
  map(&:to_h)                    # hashify
#⇒ [{:c1=>"column1_value1", :c2=>"column1_value11"},
#   {:c1=>"column1_value2", :c2=>"column1_value22"},
#   {:c1=>"column1_value3", :c2=>"column1_value33"}]

The latter might be done in one single loop, I showed chained maps to clarify steps needed.

Aleksei Matiushkin
  • 119,336
  • 10
  • 100
  • 160
0

You can use the as method:

Sequel.select(
  Sequel[:table1][:column1].as(:alias1),
  Sequel[:table2][:column2].as(:alias2)
)
Kimmo Lehto
  • 5,910
  • 1
  • 23
  • 32