[英]Ruby on Rails nested attributes not saving into database?
我正在尝试在“ Todo列表”中创建项目列表,但是,我不确定是否使用嵌套属性正确执行了此操作。 我认为使用嵌套属性是正确的尝试,因为将有大量的项目列表,并且它将与基于id的正确“ Todo列表”相关联。
的表格看起来可能会被填充记录时像例
待办事项表
id list
1 grocery shopping
2 health insurance
项目表
id todo_id name
1 1 buy milk
2 1 buy cereal
3 2 Blue Shield
4 2 Healthnet
5 1 buy cherries
尽管通过下面的尝试,我的应用程序并未将任何数据保存到Item
数据库中。
待办事项控制器
class TodoController < ApplicationController
def new
@todo = Todo.new
@todo.items.build
end
end
待办事项模型
class Todo < ActiveRecord::Base
belongs_to :user
has_many :items
accepts_nested_attributes_for :items
end
项目型号
class Item < ActiveRecord::Base
belongs_to :todo
end
待办事项视图
<%= simple_form_for(@todo) do |f| %>
<%= f.input :list %>
<%= f.simple_fields_for :items do |g| %>
<%= g.input :name %>
<% end%>
<%= f.button :submit %>
<% end %>
我可以在视图中显示name
字段,但是当我保存name
字段时,它不会保存到数据库中,但是,我可以将列表保存到数据库中,然后在尝试编辑时记录中,不再显示name
字段以进行编辑。
编辑:显示创建方法
这是我当前在Todo Controller中的Create方法
def create
@todo = Todo.new(todo_params)
respond_to do |format|
if @todo.save
format.html { redirect_to @todo, notice: 'Todo was successfully created.' }
format.json { render :show, status: :created, location: @todo }
else
format.html { render :new }
format.json { render json: @todo.errors, status: :unprocessable_entity }
end
end
end
不知道Edit是否需要一些东西,但是我只能从生成Todo支架中获得
def edit
end
编辑2显示todo_params
def todo_params
params.require(:todo).permit(:user_id, :list)
end
您必须将嵌套参数添加到强参数中
def todo_params
params.require(:todo).permit(:user_id, :list, items_attributes: [:id, :text, ...])
end
关于todo_id的注意事项:
您不需要在items_attributes
列表中添加:todo_id
,因为您已经将TODO作为上下文。
@todo = Todo.new(todo_params)
在上面的代码中,您的todo_params将包含一些链接到@todo
。 即,它类似于
@todo.items.build
它将已经与创建项目todo_id
对应@todo.id
您需要将项目添加到列入白名单的属性列表中
def todo_params
params.require(:todo).permit(
:user_id,
:list,
items_attributes: [ # you're missing this
:id,
:name
]
)
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.