【发布时间】:2019-07-17 11:22:09
【问题描述】:
在我将 rails 从 5.1 升级到 5.2 后,我开始收到以下错误:
NoMethodError: undefined method `expr' for nil:NilClass
from /gems_path/activerecord-5.2.0/lib/active_record/associations/join_dependency/join_association.rb:47:in `block in join_constraints'
from /gems_path/activerecord-5.2.0/lib/active_record/associations/join_dependency/join_association.rb:33:in `reverse_each'
from /gems_path/activerecord-5.2.0/lib/active_record/associations/join_dependency/join_association.rb:33:in `join_constraints'
from /gems_path/activerecord-5.2.0/lib/active_record/associations/join_dependency.rb:167:in `make_constraints'
from /gems_path/activerecord-5.2.0/lib/active_record/associations/join_dependency.rb:177:in `make_join_constraints'
from /gems_path/activerecord-5.2.0/lib/active_record/associations/join_dependency.rb:104:in `block in join_constraints'
from /gems_path/activerecord-5.2.0/lib/active_record/associations/join_dependency.rb:103:in `each'
from /gems_path/activerecord-5.2.0/lib/active_record/associations/join_dependency.rb:103:in `flat_map'
from /gems_path/activerecord-5.2.0/lib/active_record/associations/join_dependency.rb:103:in `join_constraints'
from /gems_path/activerecord-5.2.0/lib/active_record/relation/query_methods.rb:1026:in `build_join_query'
from /gems_path/activerecord-5.2.0/lib/active_record/relation/query_methods.rb:1008:in `build_joins'
from /gems_path/activerecord-5.2.0/lib/active_record/relation/query_methods.rb:928:in `build_arel'
from /gems_path/activerecord-5.2.0/lib/active_record/relation/query_methods.rb:903:in `arel'
from /gems_path/activerecord-5.2.0/lib/active_record/relation.rb:554:in `block in exec_queries'
from /gems_path/activerecord-5.2.0/lib/active_record/relation.rb:578:in `skip_query_cache_if_necessary'
from /gems_path/activerecord-5.2.0/lib/active_record/relation.rb:542:in `exec_queries'
from /gems_path/activerecord-5.2.0/lib/active_record/relation.rb:414:in `load'
from /gems_path/activerecord-5.2.0/lib/active_record/relation.rb:200:in `records'
from /gems_path/activerecord-5.2.0/lib/active_record/relation/delegation.rb:41:in `[]'
导致错误的代码如下所示:
class Post
has_many :comments
has_one :last_comment, -> {
joins("LEFT JOIN posts on posts.id = comments.post_id")
.where("
comments.id = (
SELECT MAX(comments.id) FROM comments
WHERE comments.post_id = posts.id
)"
)
}, class_name: "Comment"
scope :with_last_comment, -> { joins(:last_comment) }
end
我创建了this gist,其中包含有助于重现错误的完整代码。将issue_with_joins_in_scopes_in_rails_5_3.rb 下载到您的PC 并使用
ruby issue_with_joins_in_scopes_in_rails_5_3.rb
您可以查看this Github issue了解更多详情
Rails 5.2 和 5.1 中的连接有什么区别导致代码 Post.with_last_comment 在 Rails 5.2 中失败并出现错误?
如何更改 Post 模型中的 last_comment 关联和 with_last_comment 范围,以便在 Rails 5.2 中工作?
【问题讨论】:
标签: join activerecord ruby-on-rails-5.2