mysql - Rails LEFT JOIN searching and json -
i have following models:
class address < activerecord::base has_many :service_records attr_accessor :service_record end class servicerecord < activerecord::base belongs_to :address belongs_to :plant end class plant < activerecord::base has_one :service_record end i wanting perform query left joins each service record on address , each plant on service record. so, example, if have single address has 3 service records, want 3 results repeat address fields each service record while containing plant information each service record.
so far have query looking (using rails 5):
address.left_joins(service_records: :plant) that returns me correct number of repeating address results (i.e. 3 above example).
the next step struggling figure out return resulting query json structure contains each address , each unique service record. this:
[ { id: 1, address: "1234 street rd", service_record: { id: 1 plant: { id: 1 } } }, { id: 1, address: "1234 street rd", service_record: { id: 2 plant: { id: 2 } } }, { id: 1, address: "1234 street rd", service_record: { id: 3 plant: { id: 3 } } } ] if notice, have attr_accessor :service_record on address model, not sure correct approach need. or alternate approach looking appreciated!
from query, can use rails as_json options achieve want. this:
addresses = address.left_joins(service_records: :plant) addresses.as_json # => [ { id: 1, address: "1234 street rd" }, { id: 1, address: "1234 street rd" }, { id: 1, address: "1234 street rd" } ] next step include associations
addresses.as_json(include: :service_record) [ { id: 1, address: "1234 street rd", service_record: { id: 1 } }, { id: 1, address: "1234 street rd", service_record: { id: 2 } }, { id: 1, address: "1234 street rd", service_record: { id: 3 } } ] and :
addresses.as_json(include: { service_record: { include: :plant } }) # => [ { id: 1, address: "1234 street rd", service_record: { id: 1 plant: { id: 1 } } }, { id: 1, address: "1234 street rd", service_record: { id: 2 plant: { id: 2 } } }, { id: 1, address: "1234 street rd", service_record: { id: 3 plant: { id: 3 } } } ] you can fine tune result. more on over documentation.
update
if sure have 1 record in service_records array, :
def service_record service_records.first end then this
addresses.as_json(methods: :service_record) [ { id: 1, address: "1234 street rd", service_record: { id: 1 } }, { id: 1, address: "1234 street rd", service_record: { id: 2 } }, { id: 1, address: "1234 street rd", service_record: { id: 3 } } ]
Comments
Post a Comment