1

I have a simple form for creating tasks which is customized with @new_task to always create tasks. A separate form is used to update them.

#Form
<%= form_for([@project, @new_task]) do |f| %>
    <%= f.text_field :title, placeholder: 'Add a Task' %>
    <%= f.submit %>
 <% end %>

#TasksController
def show
  @projects = Project.all
  @project = Project.find(params[:project_id])
  @task = Task.find(params[:id])
  @new_task = Task.new(title: @task.title)
  @tasks = @project.tasks.all
end

The problem is when I'm on tasks/show (which calls the task ID) the form assumes it's an update and populates the text field with the task name.

I need to clear the text field so that only the "Add a Task" placeholder is visible. I've tried a number of different ways with no luck and am hoping somebody here can help.

interfab
  • 45
  • 6

1 Answers1

2

All Rails forms behave like this - they pre-populate the fields with the values stored in your variable. If you've just done @new_task = Task.new, then all the values are nil, so all the fields are empty.

If, as in your case, you've done @new_task = Task.new(:title => @task.title), then the title attribute has a value (of @task.title), so that will be displayed in the form.

If you don't want anything to be displayed, just don't pre-set values.

ArtOfCode
  • 5,702
  • 5
  • 37
  • 56
  • The problem is that I have to set the title attribute in order for the form to function properly (it needs to POST at all times rather than PATCH). Perhaps I can force the clearing of the field using JS? – interfab Nov 04 '16 at 23:46
  • @interfab That's... not the right way to do that. Where did you get that idea from? Use the `method` specifier in the `form_for` tag, as in this question: http://stackoverflow.com/q/9551330/3160466. You *can* use JS to force the field clear, but that's a hack on top of a hack and you really should use the "proper" ways instead. – ArtOfCode Nov 04 '16 at 23:50
  • I followed the help from this question: http://stackoverflow.com/questions/40413314/rails-how-to-force-a-form-to-post-rather-than-patch. Adding `method: :post` to my form doesn't work for some reason, Rails still wants to edit. – interfab Nov 05 '16 at 00:44