54

现在我有这条线:

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

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

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

4

6 回答 6

90

像这样的东西应该工作:

render :json => @programs, :include => {:insurer => {:only => :name}}, :except => [:created_at, :updated_at]
于 2013-07-18T17:42:04.880 回答
20

在使用控制器方法中的包含渲染 json 时,我遇到了相同的“无法克隆符号文件”错误。像这样避免它:

render :json => @list.to_json( :include => [:tasks] )
于 2015-09-03T15:10:34.007 回答
13

您也可以在模型级别执行此操作。

程序.rb

  def as_json(options={})
    super(:except => [:created_at, :updated_at]
          :include => {
            :company => {:only => [:name]}
          }
    )
  end
end

现在在您的控制器中:

render json: @programs
于 2015-02-18T03:52:40.723 回答
9

考虑使用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  
于 2014-09-04T13:09:12.997 回答
3

尝试这个。参考

#`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实例变量,因为我假设我们没有将它传递给视图。

于 2015-06-16T22:51:34.283 回答
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"}}
  ]
于 2017-06-23T12:26:29.037 回答