简体   繁体   中英

Separate validation file for each model in rails

I have a too many models and want to maitain separate validation and relationship files for each model in rails. Is there any way i can maintain it with rails? Any specific advantage to do it?

Your question is not clear. By "models" you mean database-backed models that use ActiveRecord, right?

Usually validation is not a "file" but is a series of statements within the model's file. Same for relationship declarations.

You can split a model's contents amongst any number of files. The technique varies depending on whether you want the other files to contain instance methods or class methods.

Easiest is to have instance methods in other files. Eg

# file foo.rb
class Foo < ActiveRecord::Base
  include FooMethods

  # --- callbacks --- #
  before_create :record_signup # "before_create" is a "callback".
  # See http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html
  # note that the method could also be from a different class altogether:
  before_save      EncryptionWrapper.new
  # See section "Types of callbacks" in the api url referred to above

  # --- relationships --- #
  belongs_to :foobar
  has_many   :bars

  # --- Class Methods --- #
  def Foo.a_method_name(id)
    ...
  end
end

~~~~~~~~~~~~~~~~~~~~~~~~~~~

# file foo_methods.rb

module FooMethods

  def method1
    ...
  end

  def method2
   ...
  end

  private

  def record_signup # define the callback method
    self.signed_up_on = Date.today
  end
end

Offhand, I don't how to put the callback override

before_create

in a different file than the model's main class file. Wouldn't be hard to figure out. But no matter how easy it would be to put in a different file, I would not recommend it from the code clarity point of view.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM