7

我有一些ManagerSoccerTeam模型。经理“拥有”许多足球队;经理也可以评论足球队,也可以评论其他经理:

经理.rb

# Soccer teams the manager owns
has_many :soccer_teams, :dependent => :restrict
# Comments the manager has made on soccer teams or other managers
has_many :reviews, :class_name => "Comment", :foreign_key => :author_id, :dependent => :destroy
# Comments the manager has received by other managers
has_many :comments, :as => :commentable, :dependent => :destroy
# Soccer teams that have received a comment by the manager
has_many :observed_teams, :through => :comments, :source => :commentable, :source_type => "SoccerTeam"

足球队.rb

# The manager that owns the team
belongs_to :manager
# Comments received by managers
has_many :comments, :as => :commentable, :dependent => :destroy
# Managers that have reviewed the team
has_many :observers, :through => :comments, :source => :author, :class_name => "Manager"

评论.rb

belongs_to :commentable, :polymorphic => true
belongs_to :author, :class_name => Manager

现在,如果我有一位经理对 SoccerTeam 发表评论,我希望找到:

  • 一个Comment物体manager.reviews在里面soccer_team.comments
  • 中的一个SoccerTeam对象manager.observed_teams
  • 中的一个Manager对象soccer_team.observers

虽然第一点和第三点一切正常,但当我打电话时,manager.observed_teams我总是得到一个空数组。要实际获得经理评论过的足球队名单,我需要使用:

manager.reviews.collect{ |review| Kernel.const_get(review.commentable_type).find(review.commentable_id) if review.commentable_type == "SoccerTeam" }

这是丑陋的。我希望简单manager.observed_teams的工作......为什么不呢?

编辑

我进一步理解了为什么它不起作用。实际上,生成的 SQL 是:

SELECT "soccer_teams".* FROM "soccer_teams" INNER JOIN "comments" ON "soccer_teams".id = "soccer_teams".commentable_id AND "comments".commentable_type = 'SoccerTeam' WHERE (("comments".commentable_id = 1) AND ("comments".commentable_type = 'Manager'))

虽然我希望它是:

SELECT "soccer_teams".* FROM "soccer_teams" INNER JOIN "comments" ON "soccer_teams".id = "comments".commentable_id AND "comments".commentable_type = 'SoccerTeam' WHERE ("comments".author_id = 1)

所以问题很简单:如何获取该查询?:foreign_key(正如预期的那样,使用ans的启发式尝试:as并没有解决问题!)。

4

1 回答 1

13

我认为您只是使用了错误的关联observed_teams。代替

has_many :observed_teams, :through => :comments, 
  :source => :commentable, :source_type => "SoccerTeam"

尝试这个:

has_many :observed_teams, :through => :reviews,
 :source => :commentable, :source_type => "SoccerTeam"

同样在,

has_many :reviews, :class_name => :comment, 
  :foreign_key => :author_id, :dependent => :destroy

:comment应该'Comment'

并且在

has_many :comments, :as => commentable, :dependent => :destroy

commmentable应该:commmentable

于 2011-02-21T21:31:03.177 回答