在Rails 4中格式化我的JSON输出

时间:2015-09-07 13:15:09

标签: ruby-on-rails json ruby-on-rails-4

我在我的控制器中使用pretty_generate,但是我收到以下错误

'只生成一代JSON对象或数组'

@celebrities = Celebrity.includes(:category)    
respond_to do |format|
  format.json { render json: JSON.pretty_generate(@celebrities.to_json(:include =>{:category => {:only => [:category]} })) }
end

我不确定为什么会收到此错误

1 个答案:

答案 0 :(得分:3)

正如错误所示,only generation of JSON objects or arrays allowed。我想你应该试试这个。

@celebrities = Celebrity.includes(:category)    
respond_to do |format|
  format.json { render json: JSON.pretty_generate(JSON.parse(@celebrities.to_json(:include =>{:category => {:only => [:category]} })))}
end