不允许的参数:ROR

时间:2018-07-08 16:14:25

标签: ruby-on-rails ruby

我是ror的新手,当我提交表格时:

<%= form_for :project, url: projects_path, html: {id:'form'} do |f| %>

    <%= f.text_field :text, placeholder: 'Новая задача'  %> 

    <%= link_to  'Отмена', '', id:'cancel_link' %>
    <%= link_to  'Отправить', projects_path, id:'submit_link' %>

<% end %>

有错误:

Parameters: {"utf8"=>"✓", "authenticity_token"=>"OR2HWCi3zVz9gB5VAmnzbEuzIwFGE58JlLrWQdNcws6FVTzqh5Cu0zvUJTUEv2O/sCvU9HuadJYr3mfA40ehGA==", "project"=>{"text"=>"NEW ITEM"}} Unpermitted parameter: :text

有两个模型:

class Project < ApplicationRecord
 has_many :todos
 validates :title, presence: true
 accepts_nested_attributes_for :todos
end


class Todo < ApplicationRecord
  belongs_to :project, required: false
end

Todo模型具有一个文本属性,应该在其中放置我们的待办事项

控制器

class ProjectsController < ApplicationController
def index
    @projects = Project.all
end

def create
    @project = Project.new(project_params)

    if @project.save
        redirect_to root_path
    end
end

def update
end

private 
    def project_params
        params.require(:project).permit(:title, todos_attributes: [:id, :text])
    end
end

项目数据库

class CreateProjects < ActiveRecord::Migration[5.2]
def change
 create_table :projects do |t|
  t.string :title
  t.string :todos

  t.timestamps
end

Todo数据库

 class CreateTodos < ActiveRecord::Migration[5.2]
 def change
   create_table :todos do |t|
     t.text :text
     t.boolean :isCompleted
     t.integer :project_id

     t.timestamps
end

我正在使用accepts_nested_attributes_for请求todo属性:todos,控制器也已在指南中注册,在我请求todos_attributes的project_params中。但是,当将表单发送到数据库时,该值为文本。他没有保存在数据库中。你能帮忙吗

2 个答案:

答案 0 :(得分:0)

要在text模型中保存Todo字段,您必须创建嵌套表单。为此使用nested_form宝石。

一个模糊的例子来展示其工作原理:

<%= nested_form_for :project, url: projects_path, html: { id: 'form' } do |f| %>
  <%= f.text_field :title, placeholder: 'Новая задача' %>

  <%= f.fields_for :todos do |todo_form| %>
    <%= todo_form.text_field :text %>
    <%= todo_form.link_to_remove "Remove this todo" %>
  <% end %>

  <p><%= f.link_to_add "Add a todo", :todos %></p>

  <%= link_to  'Отмена', '', id:'cancel_link' %>
  <%= link_to  'Отправить', projects_path, id:'submit_link' %>
<% end %>

在控制器中,具有在编辑项目的情况下删除待办事项的功能:

def project_params
  params.require(:project).permit(:title, todos_attributes: [:id, :text, _destroy])
end

在迁移CreateProjects < ActiveRecord::Migration[5.2]中,我认为您不需要todos作为字符串。

答案 1 :(得分:0)

您创建的表单有误,您需要创建一个nestead_form

它给您和Unpermitted parameter错误,因为text不是项目模型的字段,您可以在迁移文件中检查。您需要将其更改为title,因为title是项目模型的字段。

要创建嵌套表单,您需要对表单进行一些更改

<%= form_for :project, url: projects_path, html: {id:'form'} do |f| %>

   <%= f.text_field :title, placeholder: 'Новая задача'  %> 
   <%= f.fields_for :todos do |todo| %>
      <%= f.text_field :text %>
   <% end %>

   <%= link_to  'Отмена', '', id:'cancel_link' %>
   <%= link_to  'Отправить', projects_path, id:'submit_link' %>

<% end %>