Search code examples
ruby-on-railsafter-create

rails - Auto create tasks after creating a project (after_create)


a newbie here. Just started to learn development. Any help would be greatly appreciated

I have two models Project and Task. Each project will have 7 tasks. I want rails to auto create my 7 tasks after I create a project.

My Task Controller

def create
@task = Task.new(task_params)

respond_to do |format|
  if @task.save
    format.html { redirect_to @task, notice: 'Task was successfully created.' }
    format.json { render :show, status: :created, location: @task }
  else
    format.html { render :new }
    format.json { render json: @task.errors, status: :unprocessable_entity }
  end
end

end

def task_params
  params.require(:task).permit(:title, :description)
end

Solution

  • There are several ways you can do this.

    1. Via callbacks

    You can use callbacks in the Project model. Personally I do not recommend this approach since it this is not the intended use of callbacks, but it may work for you.

    class Project < class Attachment < ActiveRecord::Base
      after_create :create_tasks
    
    private
    
      def create_tasks
        # Logic here to create the tasks. For example:
        # tasks.create!(title: "Some task")
      end
    end
    

    2. Nested attributes

    You can build the child objects into the form and Rails will automatically create the child objects for you. Check out accepts_nested_attributes_for. This is more involved than using callbacks.

    3. Use a form object

    A form object can be a nice middle ground between callbacks and accepts_nested_attributes_for, but it raises the complexity a notch. Read up more about form objects here. There is also a nice Rails Casts episode on the topic, but it requires subscription.

    There are other ways to do this as well, so it's up to you to find the right approach.