Order of includes and scopes? #65

Open
kbighorse opened this Issue Mar 26, 2013 · 7 comments

Comments

Projects
None yet
3 participants
Contributor

kbighorse commented Mar 26, 2013

In the case of a model with a default_scope, includes, and other scopes, what should the order be? Includes, then default scope, then scopes below in the 'other macros' section would be my guess. Also, in my opinion, scopes should be first-class citizens in the macro-ordering section, along with attribute macros, validations, etc.

Accidentally sent that last comment before it was finished!

Here's the revision:

I prefer the following order:

  1. Includes
  2. Constant declarations (or other config stuff - though it's ugly, people do it constantly)
  3. Relationships (grouped, order is unimportant)
  4. Callbacks
  5. Scopes
  6. Validations
  7. Attr stuff
  8. Delegates
  9. And everything else built in
  10. Everything custom

Callbacks should be listed in the order they happen:

  1. save
  2. before_validation
  3. after_validation
  4. before_save
  5. before_create
  6. after_create
  7. after_save
  8. after_commit

An overall example:

class SomeModel
  include ModelHelper

  CONFIG = 'something'

  has_many :other_models
  has_and_belongs_to_many :of_something
  belongs_to :another_model

  before_create :do_before_create
  before_save :do_before_save, :and_something_else
  after_save :something
  after_commit :another_thing

  scope :some_category, where(something: false)
  scope :another_category, where(something: true)

  validate :attribute, presence: true

  attr_reader :a_reader
  attr_accessor :a_accessor
  attr_writer :a_writer

  delegate :something, to: :another_model

  # The rest of the built in stuff not named
  serialize :hash_attribute

  # Custom stuff
  searchable do
    string :attribute
  end
end

thoughts?

Contributor

kbighorse commented Mar 26, 2013

what about default_scope? just group with other scopes?

I don't often use default scopes, but if I were to I would probably make it the first in the list of scopes.

class SomeModel
  # ...

  default_scope where(deleted: false)
  scope :deleted, unscoped.where(deleted: true)
  scope :another, where(something: true)

  # ...
end
Contributor

kbighorse commented Mar 26, 2013

That's what I do currently, but that conflicts with https://github.com/bbatsov/rails-style-guide#activerecord.

I don't see any scope calls in that example (other than the default_scope), where is it suggested they should go?

We could at least specify where regular scope calls go in relation to the default_scope.

Contributor

kbighorse commented Mar 26, 2013

That's the point, it only says to put default_scope at the top, but doesn't specify where the other scopes should go. That's what I'm trying to flesh out here.

lleolin commented Feb 8, 2016

I'd like to know how one is to order scopes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment