Rails 模型范围内的关联数据
我有一个名为 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
然后就可以像这样使用它:
或者从类别模型中使用它,例如:
Then just use it like:
Or from the category model like: