I'm starting a small Rails project to register iOS devices here at the office, just to learn the framework, and I've come across the following problem:
Given two models "Device" and "Owner" with the following associations:
class Owner < ActiveRecord::Base
has_many :devices
end
class Device < ActiveRecord::Base
belongs_to :owner
belongs_to :os_version
belongs_to :device_type
end
Schemas are:
CREATE TABLE "devices" (
"id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
"uuid" varchar(255),
"imei" varchar(255),
"device_type_id" integer,
"label" varchar(255),
"os_version_id" integer,
"owner_id" integer,
"created_at" datetime,
"updated_at" datetime,
"serial" varchar(255)
);
CREATE TABLE "owners" (
"id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
"first_name" varchar(255),
"last_name" varchar(255),
"username" varchar(255),
"created_at" datetime,
"updated_at" datetime
);
I'm trying to get a controller to eagerly fetch an Owner with all its Devices, so I tried the following:
class OwnerController < ApplicationController
def list
@owners = Owner.includes(:devices).all
respond_to do |format|
format.xml { render :xml=>@owners }
开发者_Go百科 format.any(:json, :html) { render :json => @owners }
end
end
end
The controller successfully lists all owners, but the devices are nowhere to be found.
I've also tried using default scope in the Owner class, but still no good.
When using rails console
, any query using Owner.include(:devices)
fails to return device information, but Owner.first.devices
has everything in it.
Any ideas on what I might be doing wrong?
Thanks!
You need to specify that your XML and JSON views should include the devices associations:
format.xml { render :xml => @owners.to_xml(:include => :devices) }
Or, in Rails 3, to make things a little simpler:
class OwnerController < ApplicationController
respond_to :html, :json, :xml
def list
@owners = Owner.includes(:devices).all
respond_with @owners, :include => :devices
end
end
AFAIK, the XML and JSON renders don't render associates by default.
For XML, you'll have to explicitly define which associations you want rendered:
format.xml { render :xml => @owners.to_xml(:include => :devices) }
The same principle (different syntax) applies to JSON rendering.
HTH
精彩评论