Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct order of associations, scopes, validations, etc. in Rails models

Edited this old question to include an answer from below: Rubocop has it https://github.com/rubocop-hq/rails-style-guide#macro-style-methods

Rails is all about 'Convention over Configuration'. However, I haven't come across a 'standard' for the order of associations, scopes, includes, validations, ... in Rails models yet. Take for example the following, simplified, product model:

class Product < ActiveRecord::Base
  mount_uploader :logo, AssetUploader
  acts_as_taggable
  paginates_per 50

  include ActionView::Helpers::NumberHelper

  belongs_to :company

  validates_presence_of [:title, :price, :plu]

  scope :on_website, where(display: true)

  def display_price
    ...
  end
end

Is this the correct order? It's maybe not that important to many people, but I personally think it would be great if there were a convention on this.

like image 495
lafeber Avatar asked Jun 06 '13 10:06

lafeber


1 Answers

There is no such convention. But you can create one for your project and be consistent with it in all the models. This is what i follow.

class Model < ActiveRecord::Base
   #all mixins
   include Something
   extend Something

   #other stuff
   acts_as_taggable
   paginates

   #associations
   has_many :something
   belongs_to :something_else

   #validations
   validate_presence_of :something

   #scopes
   scope :something

   #instance methods
   def instance_method
   end

   #class methods
   def self.method
   end

   #private methods
   private
   def method2
   end
end
like image 54
usha Avatar answered Sep 27 '22 21:09

usha