Rails extending ActiveRecord::Base

后端 未结 9 1498
眼角桃花
眼角桃花 2020-11-22 12:38

I\'ve done some reading about how to extend ActiveRecord:Base class so my models would have some special methods. What is the easy way to extend it (step by step tutorial)?<

9条回答
  •  情歌与酒
    2020-11-22 13:14

    Rails 5 provides a built-in mechanism for extending ActiveRecord::Base.

    This is achieved by providing additional layer:

    # app/models/application_record.rb
    class ApplicationRecord < ActiveRecord::Base
      self.abstract_class = true
      # put your extensions here
    end
    

    and all models inherit from that one:

    class Post < ApplicationRecord
    end
    

    See e.g. this blogpost.

提交回复
热议问题