2

I have a form to create a new Task. Inside the form, the user can select a Client that has been previously added using another form. I'd like to give the user to add a new Client "on the fly". Here is what I've tried so far.

In my view, I have a collection_select to display the current Clients. I then use a little bit of jQuery to add a new element to this list "Add another...". When this option is selected, the select menu is replaced with a text field where the user can enter a new Client's name:

<script>
  $("#task_client_id").append('<option value=999>Add another...</option>');
  $('select[name="task[client_id]"]').change(function() {
    if ($(this).val() == "999") {
      $("#task_client_id").replaceWith('<input placeholder="Enter new client name" type="text" name="task[client_name]" id="task_client_name">');
    }
  });
</script>

This creates a new parameter called "client_name". In my Task model, I added an attr_accessor for client_name so that it will not be an "Unknown Attribute".

Then in my controller, I have the following code:

  def create
    tp = task_params
    if tp[:client_name]
      c = Client.create(name: tp[:client_name])
      tp[:client_id] = c.id
    end
    if @task.save
      redirect_to new_task_task_detail_path(@task), notice: "Task created successfully!"
    else
      render :new
    end
  end

Where task_params is the private method for strong parameters (that includes client_name).

The Client actually gets created thanks to the code, but the form still renders an error due to my validation on client_id which is not present in the params hash.

I was hoping that the part tp[:client_id] = c.id would add client_id to the params hash prior to calling @task.save, but it does not. This is confirmed by adding a fail prior to calling @task.save.

How can I insert "client_id" into the params hash prior to saving it? I have also tried merge following this: Rails 4: Insert Attribute Into Params, but could not get that to work either.

Community
  • 1
  • 1
Trinculo
  • 1,950
  • 1
  • 17
  • 22

1 Answers1

1

Just add the client_id to whatever object is validating for its existence. If @task requires a client_id, then assign @task.client_id = c.id prior to calling @task.save.

Mike S
  • 11,329
  • 6
  • 41
  • 76