Rails-如何将关联的模型数据拉入控制器json调用中



我有两个相互关联的模型。

Customer has_one :primary_contact

我想在json对象中提取这些数据,以便primary_contact模型与Customer对象相关联。

现在我的控制器这样做:

@customers = current_account.customers.all
respond_to do |format|
  format.json { render :json => @customers.to_json, :layout => false }
end

但我也想在这些客户对象中包括他们的主要联系信息。我该如何在关联的上下文中提取这些信息,以便在jQuery中获得以下数据:

value.primary_contact.name

现在,我可以使用以下命令为客户对象提取json:

value.name
value.address

根据文档,使用:include选项:

要包括关联,请使用:include

konata.to_json(:include => :posts)
# => {"id": 1, "name": "Konata Izumi", "age": 16,
#     "created_at": "2006/08/01", "awesome": true,
#     "posts": [{"id": 1, "author_id": 1, "title": "Welcome to the weblog"},
#               {"id": 2, author_id: 1, "title": "So I was thinking"}]}

若要包含关联,请使用:include。

@customers = current_account.customers.all(:include => :primary_contact)
respond_to do |format|
  format.json { render :json => @customers.to_json, :layout => false }
end

最新更新