现在我有这条线:
render json: @programs, :except => [:created_at, :updated_at]
但是,由于程序属于公司,我希望显示公司名称而不是公司ID。
如何在渲染程序时包含公司名称?
答案 0 :(得分:63)
这样的事情应该有效:
render :json => @programs, :include => {:insurer => {:only => :name}}, :except => [:created_at, :updated_at]
答案 1 :(得分:14)
我得到的相同"无法克隆符号文件"使用控制器方法从包含json渲染json时出错。像这样避免它:
render :json => @list.to_json( :include => [:tasks] )
答案 2 :(得分:8)
考虑使用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
答案 3 :(得分:8)
您也可以在模型级别执行此操作。
<强> program.rb 强>
def as_json(options={})
super(:except => [:created_at, :updated_at]
:include => {
:company => {:only => [:name]}
}
)
end
end
现在在您的控制器中:
render json: @programs
答案 4 :(得分:3)
试试这个。 Ref
#`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
成为实例变量,因为我假设我们没有将它传递给视图。
答案 5 :(得分:0)
#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"}}
]