开发者

Separate validation file for each model in rails

开发者 https://www.devze.com 2023-01-02 19:58 出处:网络
I have a too many models and want to maitain separate validation an开发者_StackOverflow社区d relationship files for each model in rails. Is there any way i can maintain it

I have a too many models and want to maitain separate validation an开发者_StackOverflow社区d 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消