在轨型号范围内的关联数据 [英] association data in rails model scope

查看:84
本文介绍了在轨型号范围内的关联数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为型号命名发布(博客文章)模型和类别。每一个职位 belongs_to的类别。每个类别都有一个名为属性固定指定帖子之前的时间量到期,因此,例如 movies_category.retainer = 30.days

我想要做的就是创建一个发布,发现所有这些过期的职位的范围。因此,举例来说,假设我是到c 30.days 的价值很难$ C $和它是适用于所有类别(因此,所有职位),该范围将

 范围:过期,拉姆达{在这里(posts.created_at<,30.days.ago)}
 

不过,而不是硬编码值 30.days.ago ,我想获得定位器从价值这篇文章的类别和基地的条件,所以是这样的:

 范围:过期,拉姆达{在这里(posts.created_at<?,
  Time.now  -  post.category.retainer)}
 

所以,投入的话:我想所有这些过期的职位,以及到期状态是由每一个职位的类别的固定值来确定(即在电影类别的职位在10天内到期,在游戏类职位过期在5天,等)

这甚至可能吗?我将需要某种形式的加入或什么的?

解决方案

 范围:过期,拉姆达{|定位器|其中(posts.created_at&所述;?,
  Time.now  - 固定)}
 

然后,只需用它喜欢的:

  Post.expired(post.category.retainer)
 

或类别的模型,如:

 高清帖子
  Post.expired(固定)
结束
 

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?

解决方案

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

这篇关于在轨型号范围内的关联数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆