[英]How to create an associated model in edit form using Rails 4?
I'm currently working on a simple app where I have the following models. 我目前正在使用一个具有以下模型的简单应用程序。
Item: 项目:
# app/models/item.rb
class Item < ActiveRecord::Base
belongs_to :category
accepts_nested_attributes_for :category
end
Category: 类别:
# app/models/category.rb
class Category < ActiveRecord::Base
has_many :items
end
What I'm trying to do is to create/update an item. 我想做的是创建/更新项目。 I have this controller and form setup. 我有此控制器和表单设置。
# app/controller/items_controller.rb
class ItemsController < ApplicationController
# GET #create
def new
@item = Item.new
end
# POST #create
def create
@item = Item.new ItemParams.build(params)
if @item.save
redirect_to @item
else
render action: 'new'
end
end
# GET #update
def edit
@item = Item.find(params[:id])
end
# PATCH #update
def update
@item = Item.find(params[:id])
if @item.update(ItemParams.build(params))
redirect_to @item
else
render action: 'edit'
end
end
class ItemParams
def self.build(params)
params.require(:item).permit(:name, :category_id, category_attributes: [:id, :name])
end
end
end
Form partial: 表格部分:
# app/views/_form.html.haml
= form_for @item do |f|
= f.text_field :name
= f.label :category
= f.collection_select :category_id, Category.all, :id, :name, { include_blank: 'Create new' }
= f.fields_for :category do |c|
= c.text_field :name, placeholder: 'New category'
= f.submit 'Submit'
You'll notice that in the form, I have a select field and a textbox. 您会注意到,在表单中,我有一个选择字段和一个文本框。 What I'm trying to do is to create a new category if the user selects the "New category" in select field and enter the name of the new category in the textfield. 我想做的是,如果用户在选择字段中选择“新类别”,然后在文本字段中输入新类别的名称,则创建一个新类别。
If the setup is correct, I should be able to create a new category from the edit form or change the category. 如果设置正确,我应该能够从编辑表单中创建新类别或更改类别。 However, I'm getting this error when I try to update an existing item. 但是,当我尝试更新现有项目时出现此错误。
ActiveRecord::RecordNotFound - Couldn't find Category with ID=1 for Item with ID=1:
Any help is greatly appreciated. 任何帮助是极大的赞赏。 Thanks. 谢谢。
You have to load the category on the new
action: 您必须在new
操作上加载类别:
def new
@item = Item.new
@item.build_category
end
And to make it work with the edit
part I recommend you add the category object to the fields_for
helper like so: 为了使其与edit
部分一起使用,我建议您将类别对象添加到fields_for
辅助程序,如下所示:
f.fields_for :category, @item.category do |c|
...
Hope this helps! 希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.