【发布时间】:2020-12-21 07:44:12
【问题描述】:
您在下面看到的 Review 类表示用户为产品提交的评论。在代码的其他地方,Review.recent 使用 product_id 调用,它只是代表单个产品的唯一编号。填写代码,使其按预期工作!
Review.recent - 此函数应返回具有指定 product_id 的最近 5 条评论(按 submit_time 排序)。
- 这个特殊的 Ruby 函数在比较两个对象进行排序时被调用。它返回 1、0 或 +1,具体取决于对象是小于、等于还是大于另一个对象。您需要按 submit_time 对项目进行排序,以便首先显示最近的项目。
set_submit_time - 在创建评论之前调用此函数。我们可以使用 Ruby 的 Time 类将 submit_time 设置为 now 以便我们知道评论的创建时间。
我是 ruby 新手,我想要这个代码用于我非常重要的工作,所以我该如何完成它,请帮助我!
class Review < ApplicationRecord
# Every Review has a product_id and submit time
attr_accessor :product_id
attr_accessor :submit_time
# Before the new record is created, we'll call the :set_submit_time method
before_create :set_submit_time
def self.recent(product_id)
# Return only the 5 newest results for this product
# Reference: https://ruby-doc.org/core-2.4.2/Enumerable.html
Review.all
end
def <=>(other_review)
# Implement the comparison function for sorting
# Reference: http://ruby-doc.org/core-2.4.2/Comparable.html
end
private
def set_submit_time
# Set the submit_time
# Reference: https://ruby-doc.org/core-2.2.4/Time.html
end
end
【问题讨论】:
-
这个问题看起来像是学校里的一些作业:)。 1.阅读guides.rubyonrails.org/active_record_callbacks.html,2.
self.submit_time <=> other_review.submit_time3.Review.where(product_id: product_id).order("submit_time desc").limit(5) -
这是一个面试题还是你想完成的教程?请展示您迄今为止所写/尝试过的内容,并说明您遇到的问题。
-
@nuaky 我尝试了你的第三点,但它给我一个错误,即未定义的方法 `where'
-
@Stefan 你是对的,因为我有一个与 HTML 和 ruby 相关的项目,但我不知道 ruby,这种语言对我来说是新的。
标签: ruby-on-rails ruby review