как сделать условное включение для полиморфной модели при использовании to_json - PullRequest
1 голос
/ 19 декабря 2010

У меня есть следующие модели:

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})

Это утверждение не работает из-за полиморфизма. Запросы не имеют связанных элементов, но рекомендации есть. Мне нужен способ условного включения предметов.

1 Ответ

1 голос
/ 20 декабря 2010

для потомков ...

пытался использовать 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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...