简体   繁体   English

Rails-如何将关联的模型数据提取到控制器json调用中?

[英]Rails - How do I pull in associated model data into a controller json call?

I have two models that are associated with each other. 我有两个相互关联的模型。

Customer has_one :primary_contact

And I would like to pull this data out in a json object so that the primary_contact model is associated with the Customer object. 而且我想将此数据提取到json对象中,以便primary_contact模型与Customer对象相关联。

Right now my controller does this : 现在,我的控制器执行此操作:

@customers = current_account.customers.all

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

But I woud like to also include in these customer objects, their primary contact info as well. 但我也想在这些客户对象中也包括他们的主要联系信息。 How would I go about pulling this information in a associated context so that I get this data in jQuery as : 我将如何在关联的上下文中提取此信息,以便在jQuery中获得以下数据:

value.primary_contact.name

Right now, I can pull the json out for the customer object with this : 现在,我可以使用以下方法为客户对象提取json:

value.name
value.address

Per the documentation , use the :include option: 根据文档 ,使用:include选项:

To include associations, use :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"}]} 

To include associations, use :include. 要包含关联,请使用:include。

@customers = current_account.customers.all(:include => :primary_contact)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM