Converting a simple query into a tricky named scope in RoR

霸气de小男生 提交于 2020-01-25 04:43:14

问题


I have a simple scoping question. I would like to do this as a scope:

if article.responses.blank?
      return false
elsif article.responses.last.passed.eql?(false)
      return true
else
   return false
end

So on the article model I would have something like this:

scope :failed_response, {
    :joins=>[:responses],
    :conditions=>["responses.passed = ?", false]
  }

The problem is, I only want instances where the most recent response failed. I'm sure these is a way to do this with either fancy sorting or some kind of nested query, but I'm stuck. Thanks!


回答1:


The only thing I can think of at the moment is a subquery inside the scope:

named_scope :failed_response, {
  :conditions => ["(SELECT passed FROM responses WHERE 
     responses.article_id = articles.id ORDER BY id DESC LIMIT 1) = ?", false]
}

I guess there is some kind of Rails way that is a bit nicer or a way without a subquery, but I can't think of it at the moment. Hope this helps though. :)




回答2:


I'd say to make it clear than clever. Have a instance method to return the last_reponse for that individual article and then have another instance method to return boolean of whether that's true or false. It may not be as fast as a name scope with single line of SQL. But I still do it the clear way for better maintainability/understanding.



来源:https://stackoverflow.com/questions/4629077/converting-a-simple-query-into-a-tricky-named-scope-in-ror

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