加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – has_many:through,:source,:source_type返

发布时间:2020-12-17 04:33:31 所属栏目:百科 来源:网络整理
导读:我有一些经理和足球队模型.一名经理“拥有”许多足球队;经理也可以评论足球队,也可以评论其他经理: manager.rb # Soccer teams the manager ownshas_many :soccer_teams,:dependent = :restrict# Comments the manager has made on soccer teams or other m
我有一些经理和足球队模型.一名经理“拥有”许多足球队;经理也可以评论足球队,也可以评论其他经理:

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"

soccer_team.rb

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

comment.rb

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

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

> manager.reviews和soccer_team.comments中的Comment对象
> manager.observed_teams中的SoccerTeam对象
> soccer_team.observers中的Manager对象

虽然一切都适用于第一点和第三点,但当我调用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:正如预期的那样,没有解决问题!).

解决方法

我认为你只是使用了observe_teams的错误关联.代替
has_many :observed_teams,:source_type => "SoccerTeam"

试试这个:

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

也在,

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

:评论应该是’评论’

并在

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

可以传达的应该是:可以传播的

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读