문제

나는 iPhone에 의해 소비되는 것에 대한 plist로 표시 할 능동적 인 레코드 결과 목록을 얻으려고 노력하고 있습니다. Plist Gem v 3.0을 사용하고 있습니다.

내 모델을 POST라고합니다. 그리고 나는 post.all (또는 배열 또는 게시물)이 PLIST로 올바르게 표시되기를 원합니다.

하나의 게시물 인스턴스에 대해 잘 작동합니다. [http://pastie.org/580902]]]

맞습니다. 내가 기대할 것입니다. 그 행동을 얻으려면 다음을 수행해야했습니다.

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

그러나 모든 게시물을 할 때 모든 것이 내가 원하는 것을 표시 할 수 없습니다. 다음은 다음과 같습니다.http://pastie.org/580909

나는 마샬링을한다. 나는 다음과 같이 더 많은 출력을 원한다 : [http://pastie.org/580914)er

결과 세트를 반복하고 plist 줄을 추가 할 수 있다고 생각합니다. 그러나 추악한 것 같습니다. 더 우아한 방법이 있다고 확신합니다.

나는 지금 Ruby에 녹슬었기 때문에 우아한 방법은 나에게 분명하지 않습니다. ActiveRecord를 무시하고 하나 이상의 레코드를 뒤로 당기는 결과 세트를 만들 수 있어야합니다. 레일에서 이것은 환경에 들어갈 것입니다 .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

다른 팁

이 페이지에서 동일한 답변을 검색하는 것을 발견했습니다. 나는 또한 당신이 올바른 접근 방식을 가지고 있다고 생각하지만, 나는 또한 초보자 (레일에)이며 올바른 방법을 확신하지 못합니다. 이것을 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 Project ReadMe에 따르면 "To_plist"와는 달리 "To_plist_node"를 구현해야합니다.

Plist :: ActiveRecord 클래스에 방출해야합니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top