使用acts_as_tree获取完全限定树的to_xml

时间:2010-04-19 17:35:03

标签: ruby-on-rails ruby ruby-on-rails-plugins acts-as-tree

我有一个使用acts_as_tree的ActiveRecord类。我正在尝试更新to_xml方法,以便在调用子记录的to_xml时,它将返回嵌套在parent / ancestor xml中的xml,以提供该资源的完全限定路径。作为一个例子,我有编译器,它是编译器/版本的父。编译器应该呈现为xml:

编译器/版本应呈现为

  

我试图通过传递一个full_qualified标志来做到这一点,但它死了'Builder :: XmlMarkup#to_ary应该返回Array'

def to_xml(options = {},& block)     options [:fully_qualified] || = true     options [:indent] || = 2     options [:builder] || = Builder :: XmlMarkup.new(:indent => options [:indent])

if options[:fully_qualified] and not parent.nil?

55:parent.to_xml(options)do | foo |         relative_options = options.dup         relative_options [:fully_qualfied] = false         relative_options [:skip_instruct] = true         relative_options.delete(:助洗剂)

    foo << to_xml(relative_options)
  end
else
  xml = options[:builder]
  xml.instruct! unless options[:skip_instruct]

66:xml.parameter(:name =&gt; name,&amp; block)     结束   端

该方法适用于编译器的情况,但编译器/版本失败:

/usr/lib/ruby/1.8/builder/xmlbase.rb:133:in method_missing' /usr/lib/ruby/1.8/builder/xmlbase.rb:133:in来电' /usr/lib/ruby/1.8/builder/xmlbase.rb:133:in _nested_structures' /usr/lib/ruby/1.8/builder/xmlbase.rb:57:in method_missing' app / models / parameter.rb:66:in to_xml' app/models/parameter.rb:55:in to_xml'

1 个答案:

答案 0 :(得分:1)

看来你不能在任何单一关联上调用to_xml。父和参数上的to_xml(两个has_one关系)都失败了,但是如果我使用find_by_id进行了查找,它就有效了:

def to_xml(options = {},&amp; block)     my_options = options.dup     my_options [:fully_qualified] = true除非my_options.has_key?(:fully_qualified)     my_options [:only] = [:name]

if my_options[:fully_qualified] and not parent.nil?
   # do block here fails with 'Builder::XmlMarkup#to_ary should return Array'
   # if called as parent.to_xml, so call on explicit lookup of parent and
   # it works
   p = self.class.find_by_id(parent_id)
   p.to_xml(my_options) do |xml|
     relative_options = my_options.dup
     relative_options[:builder] = xml
     relative_options[:fully_qualified] = false
     relative_options[:skip_instruct] = true

     to_xml(relative_options, &block)
   end
else
  super(my_options, &block)
end