0

I have a nested resource like this

resources :projects do resources :tasks end

The tasks have a field named number. Whenever I create a task I would like to give it a squential number within the parent project.

This is my model class

   class Task < ActiveRecord :: Base
 belongs_to :project

    validate_presence_of :title
    before_create :generate_number

    private
    def generate_number
        if project.tasks.nil? || project.tasks.count < 1
            self.number = 1
        else
            self.number = list.topics.count+1
        end
    end
end

I am not sure about certain things: Does this logic belongs in my Task Model or in my Project model or in a seperate class/module? What is the best before filter. (before_create, before_validation, validation)? Because there are many ways how to create a task. With a list, in a list, alone and then attach it to a list... And which filter would work in my tests so that I could setup some Fakes for example with factory girl... Because right now FactoryGirl does not always executes generate number...

This is my factory

FactoryGirl.define do 
factory :project do
    name "Hello world"
end
trait :with_tasks do
    ignore do
        number_of_tasks 3
    end
    after :create do |project,evaluator|
        @project.Factory.create_list :taks, evaluator.number_of_tasks, :project => project
    end
end

end

What would be the best. reliable way to generate a sequential custom taks number depending on the project which works in my specs as well as in production? Any best practise tips would be appreciated.

server info
  • 1,335
  • 1
  • 14
  • 24

1 Answers1

0

I would keep the before_create callback in the Task model, which would call the generate_number function. This should work in Factory girl where it would add the number if you use Factory.create, but not when you use Factory.build.

Solomon
  • 6,145
  • 3
  • 25
  • 34