【问题标题】:Hash include methods and/or nested attributes哈希包含方法和/或嵌套属性
【发布时间】:2013-04-24 04:48:10
【问题描述】:

在创建类似于使用to_json 时的哈希时是否可以包含方法或嵌套属性?

当使用 to_json 时,我可以包含 published_events 方法和一些嵌套方法:

render :json => @venue.to_json(:include => {:published_events => {:methods => :to_param, :include => :occurrences}}) 

在创建相似项目的哈希时可以这样做吗?

@area_attractions = Venue.find(:all, :conditions => ['attraction = ? AND featured = ?', true, true], :limit => 8)

hash = { :main => @main_features, :local_hotspots => @local_hotspots, :area_attractions => @area_attractions }

编辑: 无论如何,我最终还是将这个散列渲染为 JSON:

render :json => hash.to_json 

【问题讨论】:

标签: ruby-on-rails ruby


【解决方案1】:

Finder 方法返回数组,而不是哈希。试试这个:

hash = { :main => @main_features, 
         :local_hotspots => @local_hotspots, 
         :area_attractions => Hash[*@area_attractions] }

【讨论】:

    【解决方案2】:

    哈希中的项目可以/仍将包含调用 to_json 时的方法

     render :json => hash.to_json(:methods => [:image_url, :to_param, :thumb_url])
    

    【讨论】:

      猜你喜欢
      • 2013-04-30
      • 2015-08-14
      • 2015-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多