I have two tables, devices
and device_properties
.
The devices
table columns are as follows:
id
ip
mac
device_property_id
created_at
updated_at
The device_properties
table columns are as follows:
id
property_name
cli_enabled
created_at
updated_at
At the moment I have the following code to retrieve an array of devices as well as their properties:
@Data = Array.new
@Devices = Device.joins(:device_property)
@Devices.each do |d|
p = d.device_property
@Data.push({
:device => {
:id => d.id,
:ip => d.ip,
:mac => d.mac,
:created_at => d.created_at,
:updated_at => d.updated_at,
:device_property_id => p.id,
:property_name => p.property_name,
:cli_enabled => p.cli_enabled
}
})
end
I return this as JSON:
render json: {
"status" => "success",
"data" => @Data
}
Is there a better way to render this all as JSON?
I was previously using this method:
@Data = Device.select("devices.*, device_properties.*").joins(:device_property)
But I soon discovered that the id
that was being returned in the JSON was that of the device_property
and not the device
:
{
"device" : {
"id" : 13,
"ip" : "192.168.1.2",
"mac": "12:34:56:78:90:AB",
"created_at" : "Oct 24th 2016",
"updated_at" : "Oct 24th 2016",
"device_property_id" : 13,
"property_name" : "Disabled CLI",
"cli_enabled" : false
}
}
As you can see in the example, the device.id
is matching device_property.id
.