The default value is "ActiveRecord"

So, let's say I want to check for a nil in an ActiveRecord scope:

class Person < ActiveRecord::Base
  scope :closest, ->(point) {
    return nil unless point # How can I return the ActiveSupport::Relation here?
    # other code goes below
  }
end
+4
source share
3 answers

Edit / Solution

As mentioned in the comments above, and as @ahmacleod pointed out, allthis is what we are looking for

scope :closest, ->(point) {
  point.nil? ? all : where(point: point)
}

End editing

I think I found what I'm looking for, and unscoped

scope :closest, ->(point) {
  point.nil? ? unscoped : where(point: point)
}

The problem is that if I connect this, I would lose the previous areas if I use them after them.

+2
source

You can simply return self to return the default scope:

class Person < ActiveRecord::Base

  def self.closest(point = nil)
    point.nil? ? self : where(point: point)
  end

end
+2
source

point . - :

scope :closest, -> (point = '') {
  where(point: point)     
} 

, ActiveRecord:: Relation .

, :)

0
source

Source: https://habr.com/ru/post/1609373/


All Articles