开发者

association data in rails model scope

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 开发者_JAVA百科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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜