使用to_json时如何为多态模型做条件包含

时间:2010-12-18 22:57:48

标签: ruby-on-rails json models

我有以下型号:

class Feed < ActiveRecord::Base
  belongs_to :post, :polymorphic => true
end

class Request < ActiveRecord::Base
  has_one :feed, :as => :post, :dependent => :destroy
end  

class Recommendation < ActiveRecord::Base
  belongs_to :item
  has_one :feed, :as => :post, :dependent => :destroy
end  

class Item < ActiveRecord::Base
end

feed_obj.to_json(:include => {:post => :item})

该语句不适用于多态的b / c。请求没有关联的项目,但建议有。我需要一种有条件的包括物品的方式。

1 个答案:

答案 0 :(得分:1)

为子孙后代......

尝试使用as_json作为Feed模型,但是在调用super时会出现错误。请参阅下面的代码以获得解决方案:

class Feed < ActiveRecord::Base
  belongs_to :post, :polymorphic => true

  def as_json(options={})
    # Bug in Rails 3.0: Should be able to simply call super with item included when the post is a Recommendation
    # Instead, have to construct using serializable hash; leaving correct code commented out here so it can be used
    # when the bug is fixed
    #if self.post.class == Recommendation
    #  super(:include => {:post => {:include => :item}})
    #else
    #  super(:include => :post)
    #end
    if self.post.class == Recommendation
      self.serializable_hash(:include => {:post => {:include => :item}})
    else
      self.post.serializable_hash()
    end
  end
end