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.
精彩评论