Converting a simple query into a tricky named scop

2019-08-03 08:19发布

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!

2条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-08-03 09:12

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. :)

查看更多
贪生不怕死
3楼-- · 2019-08-03 09:13

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.

查看更多
登录 后发表回答