gpt4 book ai didi

ruby-on-rails - has_many :through, :source, :source_type 返回空数组

转载 作者:行者123 更新时间:2023-12-04 03:37:00 25 4
gpt4 key购买 nike

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

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"

Football_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"

评论.rb
belongs_to :commentable, :polymorphic => true
belongs_to :author, :class_name => Manager

现在,如果我有一位经理评论一个足球队,我希望找到:
  • 一个 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 进行启发式尝试并没有解决问题!)。

    最佳答案

    我认为您只是对 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

    关于ruby-on-rails - has_many :through, :source, :source_type 返回空数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5052588/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com