我有一些Manager
和SoccerTeam
模型。经理“拥有”许多足球队;经理也可以评论足球队,也可以评论其他经理:
经理.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
并没有解决问题!)。