0

I have an Active Record query that involves a JOIN using a SQL statement.

TableA.where(:b_id => "123")
      .joins("INNER JOIN TableB ON column1='value1' AND column2 = TableB.id")

where column1 and column2 belong to TableA

The reason I have to use SQL is because I don't have a relationship defined between the two tables (for other reasons), and haven't found a way to specify a ON clause on columns, using Active Record JOIN

Since I don't have a relationship defined, I cannot use :includes and hence do not have access to TableB's columns in the results. Is there a way to get TableB's data by modifying the above query?

1 Answer 1

1

You can add the columns in the select query.

TableA.select('TableA.*, TableB.column1, TableB.column2')
      .where(:b_id => "123")
      .joins("INNER JOIN TableB ON column1='value1' AND column2 = TableB.id")

NOTE: You might not see the columns in the TableA record in rails console. Use as_json to check if you got them in result

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

1 Comment

Thanks, that worked! Didn't realize I could use TableB's columns in the select.

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.