【问题标题】:rails 4 cross model named scopesrails 4 跨模型命名范围
【发布时间】:2026-02-04 03:30:02
【问题描述】:

我想要做的是创建适当的命名范围来获取 3 天前创建的登录用户的所有报告

class User < ActiveRecord::Base
    has_many :appraisals

end

class Appraisal < ActiveRecord::Base
    belongs_to :user
    has_one :report

    scope :submitted, -> { joins(:report).where("reports.created_at >= ?", 3.days.ago) }
end

class Report < ActiveRecord::Base
    belongs_to :appraisal
end

我尝试了不同的 Rails 控制台语句,但也许我用错了方法。

在 Rails 控制台中,我尝试了各种方法,但一直收到此错误

PG::UndefinedTable: 错误:表“报告”缺少 FROM 子句条目

with 语句如

user = User.find(2)
user.appraisals.submitted

有什么想法吗?

【问题讨论】:

  • 试试joins(:report).where("reports.created_at &gt;= ?", 3.days.ago)。你在数据库中的表名是什么?
  • 抱歉,我发出了嘘声。我更新了它

标签: ruby-on-rails named-scope


【解决方案1】:

joins 中,您必须像这样指定关联名称:

scope :submitted, -> { joins(:report).where("appraisal_reports.created_at >= ?", 3.days.ago) }

【讨论】:

  • appraisal_reports 可能也需要在where 中进行更改。
  • 可能。取决于表名。
最近更新 更多