gpt4 book ai didi

ruby-on-rails - Rails has_many with `through` option "loses"加入?

转载 作者:行者123 更新时间:2023-12-04 02:23:04 24 4
gpt4 key购买 nike

我有以下示例模型结构:

class Category < ActiveRecord::Base
has_many :posts

scope :active, -> { where(active: true) }
end

class User < ActiveRecord::Base
has_many :posts
has_many :visible_posts, -> { joins(:category).merge(Category.active) }, class: Post
has_many :visible_posts_comments, through: :visible_posts, source: :comments

has_many :comments
end

class Post < ActiveRecord::Base
belongs_to :category
belongs_to :user
has_many :comments
end

class Comment < ActiveRecord::Base
belongs_to :post
belongs_to :user
end

现在是 User.first.visible_posts_comments引发以下错误:
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "categories"
LINE 1: ..." = "posts"."id" WHERE "posts"."user_id" = $1 AND "categorie...

这是因为该关联执行的 SQL 如下:
2.1.2 :009 > u.visible_posts_comments.to_sql
=> "SELECT \"comments\".* FROM \"comments\" INNER JOIN \"posts\" ON \"comments\".\"post_id\" = \"posts\".\"id\" WHERE \"posts\".\"user_id\" = $1 AND \"categories\".\"active\" = 't'"

虽然 visible_posts通过添加 INNER JOIN 正常工作在 categories ,
2.1.2 :010 > u.visible_posts.to_sql
=> "SELECT \"posts\".* FROM \"posts\" INNER JOIN \"categories\" ON \"categories\".\"id\" = \"posts\".\"category_id\" WHERE \"posts\".\"user_id\" = $1 AND \"categories\".\"active\" = 't'"

为什么 visible_posts_comments好像“输”了 joins(:category)声明但保留了 merge(Category.active) ?我认为没有理由放弃 through 的连接- 有意结社。这是错误还是功能?

我正在使用 activerecord-4.1.8。

可能与此有关: https://github.com/rails/rails/issues/17904

最佳答案

我创建了一个和你一样的 rails 项目,发现了同样的问题。
关于这个问题有两点:
1. has_many :through 将从直通关系中删除“连接”,源代码:

#lib/active_record/associations/through_association.rb  line 14
def target_scope
scope = super
chain.drop(1).each do |reflection|
relation = reflection.klass.all
relation.merge!(reflection.scope) if reflection.scope

scope.merge!(
relation.except(:select, :create_with, :includes, :preload, :joins, :eager_load)
)

end
scope
end
我认为他们这样做的原因是对记录创建操作的考虑。例如。也许 u.visible_posts_comments.create(...) 会让 ActiveRecord 感到困惑
2. 为您准备的绕行方式:
class Category < ActiveRecord::Base
has_many :posts
end

class User < ActiveRecord::Base
has_many :posts
has_many :visible_posts, -> { merge(Post.active) }, class: Post
has_many :visible_posts_comments, -> { joins(:post).merge(Post.active) }, class: Comment

has_many :comments
end

class Post < ActiveRecord::Base
belongs_to :category
belongs_to :user
has_many :comments

scope :active, -> { joins(:category).merge(Category.active) }
end

class Comment < ActiveRecord::Base
belongs_to :post
belongs_to :user
end

关于ruby-on-rails - Rails has_many with `through` option "loses"加入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27275766/

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