Rails: How to force a form to post rather than patch?

≡放荡痞女 提交于 2020-01-25 21:09:48

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!