现在我有这条线:
render json: @programs, :except => [:created_at, :updated_at]
但是,由于程序属于公司,我想显示公司名称而不是公司 ID。
渲染程序时如何包含公司名称?
现在我有这条线:
render json: @programs, :except => [:created_at, :updated_at]
但是,由于程序属于公司,我想显示公司名称而不是公司 ID。
渲染程序时如何包含公司名称?
像这样的东西应该工作:
render :json => @programs, :include => {:insurer => {:only => :name}}, :except => [:created_at, :updated_at]
在使用控制器方法中的包含渲染 json 时,我遇到了相同的“无法克隆符号文件”错误。像这样避免它:
render :json => @list.to_json( :include => [:tasks] )
您也可以在模型级别执行此操作。
程序.rb
def as_json(options={})
super(:except => [:created_at, :updated_at]
:include => {
:company => {:only => [:name]}
}
)
end
end
现在在您的控制器中:
render json: @programs
考虑使用jbuilder以可维护的方式包含嵌套模型:
# /views/shops/index.json.jbuilder
json.shops @shops do |shop|
# shop attributes to json
json.id shop.id
json.address shop.address
# Nested products
json.products shop.products do |product|
json.name product.name
json.price product.price
end
end
尝试这个。参考
#`includes` caches all the companies for each program (eager loading)
programs = Program.includes(:company)
#`.as_json` creates a hash containing all programs
#`include` adds a key `company` to each program
#and sets the value as an array of the program's companies
#Note: you can exclude certain fields with `only` or `except`
render json: programs.as_json(include: :company, only: [:name])
此外,不需要创建@programs
实例变量,因为我假设我们没有将它传递给视图。
#includes is used to avoid n+1 query.
# http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations
Here is an example for the above example.Lets say you have posts and each post has many comments to it.
@posts = Post.where('id IN [1,2,3,4]').includes(:comments)
respond_to do |format|
format.json {render json: @posts.to_json(:include => [:comments]) }
end
#output data
[
{id:1,name:"post1",comments:{user_id:1,message:"nice"}}
{id:2,name:"post2",comments:{user_id:2,message:"okok"}}
{id:3,name:"post1",comments:{user_id:12,message:"great"}}
{id:4,name:"post1",comments:{user_id:45,message:"good enough"}}
]