Search code examples
ruby-on-railsmodel-associationsamoeba-gem

Set current_user.id in association (duplicate using amoeba)


I have a Tasklist & a Task Model.

I'm using the gem amoeba to duplicate one task list with its associated tasks. Both Tasklist & Task have a user_id field.

The user_id is set to NULL by default.

When I duplicate, I want the user_id to be set to the current_user.id (from Devise).

I'm able to copy the task list with the proper user_id using:

@tasklist = Tasklist.find(topic_params[:tasklist])
@tasklist.user_id = current_user.id
@tasklist.tasks.user_id = current_user.id
@tasklist.amoeba_dup.save

Tasks are also properly copied but the user_id is not updated in the copied tasks (only task list). I can't use the current_user.id in the Model with :set.

So I'm wondering how I can achieve this?


Solution

  • Here's how I solved the problem: instead of using amoeba for the associations, I did a loop in the controller for the associations, thus giving me the necessary current_user.id

    @topic = Topic.find(params[:id])
    @tasklist = Tasklist.find(topic_params[:tasklist])
    @tasklist.user_id = current_user.id
    @new_tasklist = @tasklist.amoeba_dup
    @new_tasklist.save
    @tasklist.tasks.each do |task|
      task.user_id = current_user.id
      task.tasklist_id = @new_tasklist.id
      task.amoeba_dup.save
    end