我想获得的活动记录结果列表中显示是plist由iphone被消耗。我使用的plist宝石V 3.0无

我的模型被称为帖子。我想Post.all(或任何阵列或主题)来是plist正确显示。

我有一个实例后工作正常: [ http://pastie.org/580902][1]

这是正确的,我期望的那样。要获得这种行为我不得不这样做:

class Post < ActiveRecord::Base
   def to_plist
     attributes.to_plist
   end
end

然而,当我做了Post.all,我不能得到它,以显示我想要的东西。这是发生了什么: http://pastie.org/580909

我得到编组。我想输出更是这样的: [ http://pastie.org/580914][2]

我想我可以只是迭代结果集和追加的plist字符串。但似乎丑陋,我敢肯定有一个更优雅的方式来做到这一点。

我现在是在红宝石生锈,所以优雅的方式并不明显我。好像我应该能够覆盖的ActiveRecord,使结果集是拉回多个记录采取的ActiveRecord :: Base的to_plist再拍to_plist实现。在轨,这将去environment.rb中,对吧?

有帮助吗?

解决方案

我把简单的办法:

private

  # pass in posts resultset from finds
  def posts_to_plist(posts)
    plist_array = []
    posts.each do |post|
      plist_array << post.attributes
    end
    plist_array.to_plist
  end

public

  # GET /posts
  # GET /posts.xml
  def index
    @posts = Post.all
    #@posts = [{:a=>"blah"}, {:b=>"blah2"}]

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => posts_to_plist(@posts) }
    end
  end

其他提示

我找到了这个网页搜索相同的答案。我认为你有正确的方法,但我也是一个新手(on Rails的),而不是一定要做到正确的方式。我说这application_helper.rb。似乎工作。

require 'plist'
module ApplicationHelper

  class ActiveRecord::Base
    public

    include Plist::Emit

    def to_plist 
      self.attribute_names.inject({}) do |attrs, name|
        value = self.read_attribute(name)
        if !value.nil?
          attrs[name] = value
        end
        attrs
      end
    end
  end

end

据该项目的plist README,你应该实现 “to_plist_node”,而不是 “to_plist”。

您也应该MIXIN的plist ::散发出你的ActiveRecord类。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top