问题
I have a form for creating tasks which is displayed on both projects/show and tasks/show.
The form on projects/show creates new tasks fine, but on tasks/show it wants to edit the task, since I need to call the task ID from within the show action of my tasks controller.
I need to modify this form to always create new tasks.
I tried method: post but rails still inserts <input type="hidden" name="_method" value="patch" /> into the HTML.
Here are my controllers and the form:
# Tasks Controller
def show
@projects = Project.all
@project = Project.find(params[:project_id])
@task = Task.find(params[:id])
@tasks = @project.tasks.all
end
def create
@project = Project.find(params[:project_id])
@task = @project.tasks.new(task_params)
@task.save
redirect_to @project
end
#Form
<%= form_for([@project, @task]) do |f| %>
<%= f.text_field :title %>
<%= f.submit %>
<% end %>
Is there any way to force rails to always create new tasks from this form?
回答1:
Try assigning a new task object using the existing task's attributes. That way the form will POST rather than PATCH:
# Tasks Controller
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
# ...
#Form
<%= form_for([@project, @new_task]) do |f| %>
<%= f.text_field :title %>
<%= f.submit %>
<% end %>
来源:https://stackoverflow.com/questions/40413314/rails-how-to-force-a-form-to-post-rather-than-patch