2015-01-12 48 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| 
... 

希望這會有所幫助!

相關問題