Rails 模型范围内的关联数据

发布于 2024-10-27 03:27:30 字数 769 浏览 7 评论 0原文

我有一个名为 Post(博客文章)的模型和一个名为 Category 的模型。每个帖子都属于一个类别。每个类别都有一个名为 retainer 的属性,用于指定帖子“过期”之前的时间量,例如 movies_category.retainer = 30.days

我正在尝试要做的就是为 Post 创建一个范围,查找所有“过期”的帖子。例如,假设我要对 30.days 的值进行硬编码,并将其应用于所有类别(因此适用于所有帖子),则范围将是:

scope :expired, lambda { where("posts.created_at < ?", 30.days.ago) }

但是,不要对值进行硬编码 30.days.ago,我想从帖子的类别中获取 retainer 值,并以此为基础设置条件,所以类似于:

scope :expired, lambda { where("posts.created_at < ?", 
  Time.now - post.category.retainer) }

所以用语言来说:我想获取所有过期帖子的数量,过期状态由每个帖子类别的保留值决定(即电影类别中的帖子将在 10 天后过期,游戏类别中的帖子将在 5 天后过期,等等)

这可能吗?我需要某种形式的加入或其他什么吗?

I have a model named Post (blog post) and a model named Category. Each post belongs_to a category. Each category has an attribute named retainer that specifies the amount of time before a post "expires", so for example movies_category.retainer = 30.days

What I'm trying to do is create a scope for Post that finds all of the posts which are "expired". So for example, assuming I were to hardcode the value of 30.days and it were to apply to all categories (therefore all posts), the scope would be:

scope :expired, lambda { where("posts.created_at < ?", 30.days.ago) }

However, instead of hardcoding the value 30.days.ago, I want to get the retainer value from the post's category and base the condition on that, so something like:

scope :expired, lambda { where("posts.created_at < ?", 
  Time.now - post.category.retainer) }

So put into words: I want to get all of the posts which are expired, and the expiration status is determined by each post's category's retainer value (i.e. posts in the movies category expire in 10 days, posts in the games category expire in 5 days, etc.)

Is this even possible? Would I require some form of join or something?

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

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

发布评论

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

评论(1

沫雨熙 2024-11-03 03:27:30
scope :expired, lambda { |retainer| where("posts.created_at < ?", 
  Time.now - retainer) }

然后就可以像这样使用它:

Post.expired(post.category.retainer)

或者从类别模型中使用它,例如:

def Posts
  Post.expired(retainer)
end
scope :expired, lambda { |retainer| where("posts.created_at < ?", 
  Time.now - retainer) }

Then just use it like:

Post.expired(post.category.retainer)

Or from the category model like:

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