ModelA
- id
- c_id
- d_id
ModelB
- id
- name
- c_id
- d_id
Shared columns for ModelA
and ModelB
are c_id
and d_id
.
SELECT
A.id, B.name
from
ModelA ASA
LEFT JOIN ModelB ASB
ON A.c_id = B.c_id AND A.d_id = B.d_id
How do I retrieve data like this with Rails (ActiveRecord)?
ruby-on-rails mysql sql rails-activerecord
Use joins
to write as follows:
ModelA.joins(%{
LEFT JOIN model_bs
ON model_a.c_id = model_b.c_id AND model_a.d_id = model_b.d_id
}).select("*,model_b.name ASb_name") .map {|a|a.b_name}
where model_a
, model_b
is the table name.The record you get is an instance of ModelA, but name
can be obtained through the singular method name
.
If you specify a compound key in the ON clause, there is no other way but to write SQL (part of ) directly.Probably.
© 2025 OneMinuteCode. All rights reserved.