4
\$\begingroup\$

How can I DRY these scopes?

 scope :reputed, -> {
 joins{reputations.outer}.
 where{['coalesce(rs_reputations.value, 0) > ? OR purchases.force_active = ?', LOWEST_VOTE, true]}
 }
 scope :reputed_or_mine, ->(user) {
 joins{reputations.outer}.
 where{['coalesce(rs_reputations.value, 0) > ? OR purchases.force_active = ? OR purchases.user_id = ?', LOWEST_VOTE, true, user.id]}
 }
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Sep 11, 2012 at 12:39
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$
'coalesce(rs_reputations.value, 0) > ? OR purchases.force_active = true OR (? AND purchases.user_id = ?)',
LOWEST_VOTE,
!user.id.nil?,
(if user.id.nil? then -1 else user.id end)

This is semantically equivalent to both, but the AND in the third clause prevents it from having an effect when there is no user.id.

answered Sep 18, 2012 at 4:59
\$\endgroup\$
4
  • \$\begingroup\$ @ck3g, can you be more specific about the errors? \$\endgroup\$ Commented Sep 24, 2012 at 17:30
  • \$\begingroup\$ Sure. user.id will throw error Undefined method id for NilClass or called id for nil... if user will not passed. Your solution is based on this. \$\endgroup\$ Commented Sep 24, 2012 at 23:21
  • \$\begingroup\$ @ck3g, Understood. In that case, I'd declare the user argument with a default value that has an id of nil. \$\endgroup\$ Commented Sep 25, 2012 at 1:04
  • \$\begingroup\$ with OR in there, you don't get much other options. I don't support collecting in several steps and merging afterwards, because that's what a relational database is usually the best at. So I'm upvoting this solution. \$\endgroup\$ Commented Jun 21, 2013 at 6:59

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.