views:

41

answers:

1

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?

A: 

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.

Larry K
Thanks larry for the quick reply..Can i add before_validation,after_save,after_create methods in the module? and is it work if i simply include that module in my class?? as it's works as things working together in one class.
krunal shah
# file foo.rb class Foo < ActiveRecord::Base include FooMethods # --- 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 end That's the perfect solution which i want. But i have another question is.is there any specific advantage with loading ? if we will maintain instance methods in another module.
krunal shah
@krunal, your comment is line-wrapped and unreadable. I suggest that you add it to your original q preceded by "Added" or some such.Also, remember to upvote answers that are useful and mark as "answered" the one that solves your problem.Re: Loading: no important difference if having multiple source files is of real help to you.Re: before_validation etc, see updated answer
Larry K
Thanks larry...
krunal shah