2015-01-12 50 views
0

我目前正在一个简单的应用程序,我有以下模型。如何使用Rails 4在编辑表单中创建关联的模型?

项目:

# app/models/item.rb 
class Item < ActiveRecord::Base 
    belongs_to :category 

    accepts_nested_attributes_for :category 
end 

类别:

# app/models/category.rb 
class Category < ActiveRecord::Base 
    has_many :items 
end 

我试图做的是创建/更新项目。我有这个控制器和窗体设置。

# 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 

表部分:

# 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' 

你会发现,在形式上,我有一个选择栏和一个文本框。我想要做的是创建一个新类别,如果用户在选择字段中选择“新类别”并在文本字段中输入新类别的名称。

如果设置正确,我应该可以从编辑窗体创建新类别或更改类别。但是,当我尝试更新现有项目时出现此错误。

ActiveRecord::RecordNotFound - Couldn't find Category with ID=1 for Item with ID=1:

任何帮助是极大的赞赏。谢谢。

回答

1

你完全可以装载在new作用类别:

def new 
@item = Item.new 
@item.build_category 
end 

,并使其与edit一部分工作,我建议你的类对象添加到fields_for帮手,像这样:

f.fields_for :category, @item.category do |c| 
... 

希望这会有所帮助!

相关问题