首页 > 解决方案 > 无法在 Rails 5 中的 form_for 中提交表单和添加数据

问题描述

当我单击从 todo_item 呈现表单的 todo_list/show 中的提交按钮时,地址框中的 url 突然发生了变化,它包含了真实性令牌和 utf8,其中的参数也仅在 url 中可见。这就是为什么控制器没有被触发的原因。附上代码:

路线

Rails.application.routes.draw do
  get 'todo_items/create'
  resources :todo_lists do
    resources :todo_items
  end

  root "todo_lists#index"
  # For details on the DSL available within this file, see 
  http://guides.rubyonrails.org/routing.html
end

控制器 todo_item

class TodoItemsController < ApplicationController

  before_action :todo_list_params 

  def create
    @todo_list = TodoList.find(params[:todo_list_id])

    @todo_item = @todo_list.todo_items.create(params_item)
    redirect_to " todo_lists#index"  
  end

  private

  def todo_list_params
    @todo_list = TodoList.find(params[:todo_list_id])
  end   

  def params_item
    params_item = params.require(:todo_item).permit(:content)  
  end  

end

end

表格部分

<%= form_for([@todo_list , @todo_list.todo_items.build]) do |f| %>
  <%= f.text_field :content , placeholder: "write the content here"  %>
  <%= f.submit  %>
<% end %>

添加日志:上面的日志是在其他控制器中成功创建数据,在这个问题。你可以很容易地看到底部日志有奇怪的 URL 和参数如何修复它: 日志

标签: ruby-on-railscontrollerruby-on-rails-5form-for

解决方案


1)=> 路线.rb

Rails.application.routes.draw do
  root "todo_lists#index"
  #get 'todo_items/create'
  resources :todo_lists, except: [:index] do
    resources :todo_items
  end
end

2)=> 运行rake routes

todo_list_todo_items POST       /todo_lists/:todo_list_id/todo_items(.:format)     todo_items#create

3)_form.html.erb(通过运行 rake 路由将 url 替换为todo_lists#create路由。)

<%= form_for @todo_list.todo_items.new, url: todo_list_todo_items_path(todo_list_id: @todo_list.id) do |f| %>
  <%= f.text_field :content , placeholder: "write the content here"  %>
  <%= f.submit  %>
<% end %>

推荐阅读