在 Rails 中渲染 JSON 时包含关联模型

在 Rails 中渲染 JSON 时包含关联模型

问题描述:

现在我有这条线:

 render json: @programs, :except => [:created_at, :updated_at]

但是,由于程序属于公司,我想显示公司名称而不是公司 ID.

However, since a Program belongs_to a Company I would like to show the Company name instead of the Company Id.

如何在渲染程序时包含公司名称?

How can I include the company name when rendering Programs?

这样的事情应该可行:

render :json => @programs, :include => {:insurer => {:only => :name}}, :except => [:created_at, :updated_at]