简体   繁体   中英

Rails: How to clear an edit form?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM