ruby-on-rails - 无法在 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 和参数如何修复它: 日志
解决方案
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 %>
推荐阅读
- javascript - 在 Crafty.js 中以实体为中心?
- node.js - .catch((err) => { 在第一个括号处出错
- javascript - 以前可以通过 Javascript 访问 HTTP 请求
- x86 - CPU 如何“准确地”读取和执行 bios 代码?
- sql - 使用默认值填充雪花表而不从文件数据中选择默认列值
- python - Python中的求和值
- python - 检查字符串以在 spark 数据框中创建新列
- python - inverseTransform 是否应该是模型进行预测的静态方法
- c# - 如何使用 c# 将 1606813200000 转换为 2020-12-01T09:00:00.000Z
- mysql - 我如何在 sql 中将我的 id null 修改为 not null