Uploaded image for project: 'Mongoid'
  1. Mongoid
  2. MONGOID-1530

Calling .unscoped on HABTM relationship doesn't work

    • Type: Icon: Task Task
    • Resolution: Done
    • 2.4.0
    • Affects Version/s: None
    • Component/s: None
    • Labels:

      I am running on Mongoid 2.2.4.

      class Calendar
      include Mongoid::Document
      include Mongoid::Paranoia
      include Mongoid::MultiParameterAttributes

      has_and_belongs_to_many :days

      def days_by_title
      days.unscoped.asc(:title)
      end
      end

      class Day
      include Mongoid::Document
      include Mongoid::Timestamps
      include Mongoid::Versioning
      include Mongoid::Paranoia

      has_and_belongs_to_many :calendars

      default_scope asc(:pos)

      field :pos, :type => Integer
      field :title, :default => "New Day"
      end

      Now in after creating a new calendar in the database, try running this in the rails console:

      > Calendar.first.days_by_title.options
      => {:sort=>[[:pos, :asc], ["title", :asc]]}

      It ignores the call to .unscoped on the days. Must be because it's a HABTM relationship. Not sure if this is by design but it sure would be nice if you could call .unscoped in a situation like this and it would return the days without the default scope (it always returns the relationship with the default scope).

      I was able to do a workaround by changing the days_by_title method like such:

      def days_by_title
      Day.unscoped.any_in(:calendar_ids => [_id]).asc(:title)
      end

      but it's not as clean or as nice. You'll have to forgive me if this issue has already been addressed in a newer version of Mongoid. I haven't upgraded because we are using MongoHQ, which hasn't rolled their production databases over to MongoDB >= 2.0, so I haven't been able to upgrade Mongoid to the most recent gem version.

            Assignee:
            Unassigned Unassigned
            Reporter:
            batter batter
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved: