2010-12-18 53 views
1

时,我有以下型号:怎么办条件包括对多态模型中使用to_json

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

为后人...

试图用as_json为饲料的模式,但调用超时,有一个错误。请参阅以下代码以获取解决方案:

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