【问题标题】:Not able submit form and add data in form_for in Rails 5无法在 Rails 5 中的 form_for 中提交表单和添加数据
【发布时间】:2018-07-06 19:03:50
【问题描述】:

当我单击 todo_list/show 中从 todo_item 呈现表单的提交按钮时,地址框中的 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和参数如何修复它: logs

【问题讨论】:

  • 你可以定义method: :post和form_for参数。
  • @Gokulp 默认 http_method 类型为post 无需添加。
  • 如果对您有帮助,请随时接受/投票。

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


【解决方案1】:

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 %>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-15
    • 2018-06-19
    相关资源
    最近更新 更多