association data in rails model scope

谁都会走 提交于 2019-12-22 23:47:22

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/5456278/association-data-in-rails-model-scope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!