Rails 3:如何使用相关对象上的方法?

发布于 2024-12-17 06:13:16 字数 803 浏览 3 评论 0原文

我正在使用 Rails 3.1 更新网站并添加一些功能。该应用程序跟踪一组站点的测试。最初,我将每个测试的成绩存储为“测试”表中的一列,但现在我创建了一个名为“评论”的新模型,以保存每个测试分配的成绩和评论的历史记录。模型如下所示:

class Site < ActiveRecord::Base
  has_many :tests
  has_many :reviews, :through => :tests

class Test < ActiveRecord::Base
  has_many :reviews
  belongs_to :site

class Review < ActiveRecord::Base
  belongs_to :test
  has_one :user

以前,我可以在站点模型中执行类似的操作来获取有关成绩的一些报告数据:

def total_a_grades
  tests.count(:conditions => "reviewer_grade = 4 and review_status = 3")
end

由于成绩现在不在测试模型中,我创建了此方法来访问每个测试的最新成绩

def last_grade
  return reviews.find(:last).grade
end

:可以很好地在测试视图中显示最新的成绩,但如何在站点级别使用它?由于该值现在采用的方法未存储在数据库中,因此我不知道如何使用它,并且在主要的在线教程/截屏网站上找不到与此相关的任何内容。

预先感谢您的帮助!

I'm updating a site with Rails 3.1 and adding some features. This application tracks tests for a collection of sites. Originally I was storing the grade for each test as a column in the Tests table but now I have created a new model called Reviews to keep a history of grades and comments assigned each test. The models look like this:

class Site < ActiveRecord::Base
  has_many :tests
  has_many :reviews, :through => :tests

class Test < ActiveRecord::Base
  has_many :reviews
  belongs_to :site

class Review < ActiveRecord::Base
  belongs_to :test
  has_one :user

Previously I could do something like this in the Site model to get some reporting data on grades:

def total_a_grades
  tests.count(:conditions => "reviewer_grade = 4 and review_status = 3")
end

Since the grades are now out of the Test model I created this method to access the most recent grade for each test:

def last_grade
  return reviews.find(:last).grade
end

This works fine for displaying the most recent grade in the test view, but how can I use it at the site level? Since the value is now in a method that's not stored in the database, I don't know how to work with it and can't find anything related to this at the major online tutorial/screencast sites.

Thanks in advance for your help!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

笑梦风尘 2024-12-24 06:13:16

joins 方法允许访问 has_many :through 关联的属性。或者从所需的关联开始,系统会为您提供所需的连接。

  tests.joins(:reviews).where("reviews.grade = 5").count

  reviews.where("grade = 5").count

来源:

The joins method allows access to the has_many :through association's attributes. Or start with the desired association, and the required joins are included for you.

  tests.joins(:reviews).where("reviews.grade = 5").count

  reviews.where("grade = 5").count

sources:

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文