Alb*_*ini 7 model-view-controller ruby-on-rails has-many has-many-polymorphs has-many-through
我得到了一些Manager和SoccerTeam模特.一名经理"拥有"许多足球队; 经理也可以评论足球队,也可以评论其他经理:
manager.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"
Run Code Online (Sandbox Code Playgroud)
soccer_team.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"
Run Code Online (Sandbox Code Playgroud)
comment.rb
belongs_to :commentable, :polymorphic => true
belongs_to :author, :class_name => Manager
Run Code Online (Sandbox Code Playgroud)
现在,如果我有一位经理对SoccerTeam发表评论,我希望找到:
Comment物体在里面manager.reviews和里面soccer_team.commentsSoccerTeam对象manager.observed_teamsManager对象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" }
Run Code Online (Sandbox Code Playgroud)
这很难看.我希望简单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'))
Run Code Online (Sandbox Code Playgroud)
虽然我希望它是:
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)
Run Code Online (Sandbox Code Playgroud)
所以问题很简单:如何获得该查询?(正如预期的那样,使用:foreign_keyans 进行启发式尝试:as并没有解决问题!).
zet*_*tic 13
我认为你只是使用了错误的关联observed_teams.代替
has_many :observed_teams, :through => :comments,
:source => :commentable, :source_type => "SoccerTeam"
Run Code Online (Sandbox Code Playgroud)
试试这个:
has_many :observed_teams, :through => :reviews,
:source => :commentable, :source_type => "SoccerTeam"
Run Code Online (Sandbox Code Playgroud)
也在,
has_many :reviews, :class_name => :comment,
:foreign_key => :author_id, :dependent => :destroy
Run Code Online (Sandbox Code Playgroud)
:comment 应该 'Comment'
并在
has_many :comments, :as => commentable, :dependent => :destroy
Run Code Online (Sandbox Code Playgroud)
commmentable 应该 :commmentable
| 归档时间: |
|
| 查看次数: |
6133 次 |
| 最近记录: |