一千萬個為什麽

搜索

Ruby數據結構呈現某種JSON格式

[
   {
      "id":"123",
      "name":"House"
   },
   {
      "id":"1456",
      "name":"Desperate Housewives"
   },
   {
      "id":"789",
      "name":"Dollhouse"
   },
   {
      "id":"10",
      "name":"Full House"
   }
]

如何渲染從Ruby中生成這種JSON格式?我擁有來自DB(@result)的所有數據,並且不知道在Ruby中使用什麽數據結構,當我這樣做時將呈現給它:

respond_to do |format|    
    format.json { render :json => @result}
end

@result應該是什麽數據結構,我如何叠代生成它?謝謝!

最佳答案

If @result is an array of ActiveRecord model instances then render :json => @result will produce something like what you are after, but will include all the attributes of the model (render calls to_json on the object you pass it unless it is a string).

要僅包含id和name屬性,可以使用:only 參數=“nofollow noreferrer”> to_json

respond_to do |format|    
  format.json { render :json => @result.to_json(:only => [:id, :name] }
end

或者,您可以創建僅包含所需屬性的Hash對象數組:

respond_to do |format|    
  format.json { render :json => 
                  @result.collect {|o| {:id => o.id, :name => o.name} } }
end

Edit: See @dt's comment below. There is an attribute in the model named text that needs to be output as name. This can be done by creating an alias for text in the model:

class Model < ActiveRecord::Base
  alias_method :name, :text

並使用:methods 包含名稱:

respond_to do |format|    
  format.json { render :json => @result.to_json(:only => :id, :methods => :name }
end

或者,可以使用哈希方法數組重命名該屬性:

respond_to do |format|    
  format.json { render :json => 
                  @result.collect {|o| {:id => o.id, :name => o.text} } }
end

轉載註明原文: Ruby數據結構呈現某種JSON格式