如何在json渲染中获取完整的belongs_to对象?

基本上,我有一个对象belongs_to:companies,并具有:company_id属性。 当我渲染json:@ coupons时,JSON是否可能包含其所有者的属性而不是company_id?

你可以做类似render :json => @coupons.to_json(:include => :company)事情render :json => @coupons.to_json(:include => :company) ,至少它似乎与我在rails 2.3.8中的初始测试一起工作。

编辑使用的答案:include => :company而不是:include => :companies

如果您需要保持json尽可能紧凑,最好使用自定义模型方法仅返回所需的数据。 我最终向父模型添加了一个自定义的as_json方法,并使用methods选项返回相关对象数据的子集。 使用include将包含相关模型的完整json序列化。

 def as_json(options={}) super( :only => [:id, :name], :methods => [ :organization_type_name, ] ) end def organization_type_name self.organization_type.name end 

首先,你的约定是错误的。

它应该是

//在coupon.rb中

 belongs_to :company 

在渲染对象时执行此操作

 render json: @coupon.as_json(include: :company)