ruby Rails关联未正确关联

64jmpszr  于 12个月前  发布在  Ruby
关注(0)|答案(1)|浏览(106)

这样做的目的是让评论属于属于用户的文章:

class User < ApplicationRecord
  has_one :profile
  has_many :articles, -> {order 'published_at DESC, title ASC'}, dependent: :nullify          
  has_many :replies, through: :articles, source: :comments
end
class Article < ApplicationRecord
  validates :title, :body, presence: true 

  belongs_to :user
  has_and_belongs_to_many :categories
  has_many :comments

  def long_title
    "#{title} - #{published_at}"
  end
end
class Comment < ApplicationRecord
  belongs_to :article
end

我从控制台得到的是:

irb(main):048> user.replies
=> []

但是!

irb(main):049> user.replies.all
  Comment Load (0.7ms)  SELECT "comments".* FROM "comments" INNER JOIN "articles" ON "comments"."article_id" = "articles"."id" WHERE "articles"."user_id" = ? ORDER BY published_at DESC, title ASC  [["user_id", 3]]
=> 
[#<Comment:0x0000ffff802d1420
  id: 1,
  article_id: 1,
  name: "guest",
  email: "[email protected]",
  body: "comment text",
  created_at: Tue, 03 Oct 2023 22:05:04.136672000 UTC +00:00,
  updated_at: Tue, 03 Oct 2023 22:05:04.136672000 UTC +00:00>]

有人能解释一下为什么用户.replies是空的,但.all显示。
当我只返回Articles.last.comments(只有1条评论和文章)时,它会返回评论。那么,为什么当我要求的时候,文章没有把它交给用户呢?

t9aqgxwy

t9aqgxwy1#

这可能是由于ActiveRecord查询缓存。
在您的控制台中,您可能首先调用了user.replies,从UI添加了注解,然后从控制台调用了user.replies。所以控制台只返回缓存的值。如果你注意到,没有SQL语句(即,Comment Load ...)之前返回结果。
运行user.replies.all时,可以看到打印出的SQL语句。
您可以尝试先运行user.reload,然后再运行user.replies,您应该会得到与调用user.replies.all时相同的结果。
您可能只会在控制台中遇到此问题。控制台适合进行初始测试,但最好在浏览器中进行测试和/或通过自动测试来检查您的请求的实际行为。

相关问题