0

I have two different active record queries that I am combining into one query. The queries is of two different tables, and has different column names. Once I combine the two queries together, I want to be able to sort it be one of the rows that contains a date. However, in "Query1" the date is called startdate. In "Query2", the date is called starts_at. I was hoping to be able to use a select alias for the Query1 to return startdate as starts_at, but after spending two days exhausting that option with no resolution (apparently select as doesn't work), I am hoping there is a way to sort the combined queries short of having to write my own sorting method.

As an example, the code I am using is similar to:

@Query1 = Course.select(:id,:city,:start_date).where(...)
@Query2 = Workshop.select(:id,:topic,:starts_at).where(...)

@CombinedQuery = Query1 + Query2

I want to sort @CombinedQuery so that the dates are of ascending order, but in a way that the results of Query1 and Query2 are sorted together. Is there any easy way of doing this?

Thanks!

1 Answer 1

2

To sort your @CombinedQuery in Ruby, here's a way:

@CombinedQuery.sort_by do |record|
  if record.respond_to? :startdate
    record.startdate
  elsif record.respond_to? :starts_at
    record.starts_at
  end
end

A side note: If you want to follow ruby naming conventions, then you should rename @Query1 and @Query1 to lowercase @query1 and @query2 respectively. The @CombinedQuery should be changed to snakecase @combined_query

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.