0

This problem is occurring on squeel 1.0.11. I have submitted an issue but thought the community may have an answer already.

I have two relationships to the same table in my model, and I'm using those two relationships in the join of two different scopes.

class Log < ActiveRecord::Base
  attr_accessible :created_by_id, :updated_by_id
  belongs_to :created_by, class_name: "User"
  belongs_to :updated_by, class_name: "User"
  scope :suggested,
    joins{created_by}.
    where{(created_by.can_admin_logs == false) | 
          (created_by.can_admin_logs == nil)}
  scope :not_edited,
    joins{updated_by}.
    where{(updated_by.can_admin_logs == false) |
          (updated_by.can_admin_logs == nil)}
end

When those scopes are changed together, the sql is incorrect.

Log.suggested.not_edited.to_sql

SELECT "logs".* FROM "logs" INNER JOIN "users" ON "users"."id" = "logs"."created_by_id" INNER JOIN "users" "updated_bies_logs" ON "updated_bies_logs"."id" = "logs"."updated_by_id" WHERE (("users"."can_admin_logs" = 'f' OR "users"."can_admin_logs" IS NULL)) AND (("updated_bies_logs"."can_admin_logs" = 'f' OR "updated_bies_logs"."can_admin_logs" IS NULL))

I've tinkered with various changes to fix the updated_bies_logs problem but haven't found a solution.

The release notes for 1.0.11 looked like they addressed this, but I updated my gem and the problem is still here.

barelyknown
  • 5,510
  • 3
  • 34
  • 46

2 Answers2

2

In addition to jdoe's answer, you may want to also wrap your scopes in lambdas, to avoid execution on loading the model. Be aware that there are some gotchas when it comes to lambdas around scopes: http://ryreitsma.blogspot.com.au/2011/07/ruby-on-rails-3-chaining-scopes-with.html

Dave Reece
  • 35
  • 8
0

You've made some twisted scopes. It's not surprisingly that you made your squeel to squeal :)

I would make it something like:

# in User
scope :cannot_admin_logs, where{can_admin_logs.eq_any [false, nil]}

# in Log 
scope :suggested,  joins{created_by}.merge(User.cannot_admin_logs)
scope :not_edited, joins{updated_by}.merge(User.cannot_admin_logs)
jdoe
  • 15,665
  • 2
  • 46
  • 48