你好我已經爲我的Rails應用程序創建了一個基本的REST控制器,我努力讓我的ActiveRecord模型加入請求。在ActiveRecord中自動加入關係
我的目標是要完成這樣的事情:
請求:GET /預約 響應:
[
{
"id":1,
"customer_id":3,
"customer":{
"name":"John Doe"
},
"date":"2011-11-11T00:00:00.000Z",
"created_at":null,
"updated_at":null,
"employee_id":1,
"employee":{
"name":"Jane Doe"
}
}
]
但是我只是得到這個:
[
{
"id":1,
"customer_id":3,
"date":"2011-11-11T00:00:00.000Z",
"created_at":null,
"updated_at":null,
"employee_id":1
}
]
這裏是我的基地REST控制器:http://pastebin.com/gQqBNeCH 你可以閱讀整個事情,如果你想,否則你可以閱讀代碼我是FOC使用上:
def index
@objects = get_class().all
@objects.each do |x|
x.get_relations
end
render json: @objects
end
這裏是我的約會模式
class Appointment < ActiveRecord::Base
belongs_to :customer
belongs_to :employee
attr_accessor :customer
validates :customer_id, presence: true, :numericality => {
:only_integer => true,
:allow_blank => false,
:greater_than => 0
}
validates :employee_id, :numericality => {
:only_integer => true,
:allow_blank => false,
:greater_than => 0
}
validates :date, presence: true
def get_relations
@customer = Customer.find(self.customer_id)
end
end
我原來的方法,只是使用像這樣的成員變量:
def get_relations
@customer = Customer.find(self.customer_id)
end
但是它看起來像ActiveRecord的具有某種它使用render運行的序列化方法。有關如何將我的belongs_to關係附加到該對象的任何建議?
+1 ......對於寫得很好,格式化的問題。好人!!!用於JBuilder的 – 2014-11-14 16:44:36