Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 获取要显示为plist的活动记录_Ruby_Activerecord_Plist - Fatal编程技术网

Ruby 获取要显示为plist的活动记录

Ruby 获取要显示为plist的活动记录,ruby,activerecord,plist,Ruby,Activerecord,Plist,我正在尝试获取一个活动记录结果列表,以显示为iphone使用的plist。我使用的是plistgemv3.0 我的模特叫波斯特。我希望Post.all(或任何数组或Posts)正确显示为Plist 我有一个帖子实例可以使用: [ 这是正确的,我所期望的。为了得到那种行为,我必须这样做: class Post < ActiveRecord::Base def to_plist attributes.to_plist end end class Post“blah2”}

我正在尝试获取一个活动记录结果列表,以显示为iphone使用的plist。我使用的是plistgemv3.0

我的模特叫波斯特。我希望Post.all(或任何数组或Posts)正确显示为Plist

我有一个帖子实例可以使用: [

这是正确的,我所期望的。为了得到那种行为,我必须这样做:

class Post < ActiveRecord::Base
   def to_plist
     attributes.to_plist
   end
end
class Post
但是,当我发布Post.all时,我无法让它显示我想要的内容。下面是发生的情况:

我得到编组。我希望输出更像这样: [

我想我可以迭代结果集并附加plist字符串。但是看起来很难看,我相信有一种更优雅的方法可以做到这一点


我现在对Ruby很生疏,所以这种优雅的方式对我来说并不明显。似乎我应该能够覆盖ActiveRecord,并生成能够拉回多个记录的结果集,将ActiveRecord::Base应用到plist,并实现另一个应用到plist。在rails中,这将放在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
private
#从查找中传入posts结果集
def posts_至_plist(posts)
plist_数组=[]
posts.每个do | post|
plist_数组“blah”},{:b=>“blah2”}]
回应待办事项|格式|
format.html#index.html.erb
format.xml{render:xml=>posts_to_plist(@posts)}
结束
结束

我发现此页面正在搜索相同的答案。我认为您的方法是正确的,尽管我也是一名新手(在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项目自述,您应该实现“to_plist_node”,而不是“to_plist”

您还应该将Plist::Emit混合到ActiveRecord类中