开发者

how to do conditional include for polymorphic model when using to_json

I have the following 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 =&g开发者_如何学编程t; :destroy
end  

class Item < ActiveRecord::Base
end

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

The statement doesn't work b/c of the polymorphism. Requests don't have an associated item, but recommendations do. I need a way of conditionally including items.


for posterity...

tried to use as_json for the Feed model, but there's a bug when calling super. See code below for solution:

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜