Entry
モデルとモデルがCategory
あり、エントリには多くのカテゴリを含めることができます (を介してEntryCategories
):
class Entry < ActiveRecord::Base
belongs_to :journal
has_many :entry_categories
has_many :categories, :through => :entry_categories
end
class Category < ActiveRecord::Base
has_many :entry_categories, :dependent => :destroy
has_many :entries, :through => :entry_categories
end
class EntryCategory < ActiveRecord::Base
belongs_to :category
belongs_to :entry
end
新しいエントリを作成するときは、 を呼び出して作成します@journal.entries.build(entry_params)
。ここentry_params
で、 はエントリ フォームのパラメータです。ただし、カテゴリが選択されていると、次のエラーが発生します。
ActiveRecord::HasManyThroughCantDissociateNewRecords in Admin/entriesController#create
Cannot dissociate new records through 'Entry#entry_categories' on '#'. Both records must have an id in order to delete the has_many :through record associating them.
2 行目の「#」はそのままであることに注意してください。オブジェクトを出力しません。
フォームのカテゴリ選択ボックスにcategories
andという名前を付けてみましたcategory_ids
が、どちらも違いはありません。いずれかが にあるentry_params
場合、保存は失敗します。カテゴリが選択されていない場合、または( )categories
から削除した場合、保存は適切に機能しますが、明らかにカテゴリは保存されません。entry_params
@entry_attrs.delete(:category_ids)
Entry レコードが保存される前に EntryCategory レコードが作成されようとしていることが問題のように思えますか? ビルドはそれを処理するべきではありませんか?
アップデート:
要求された schema.rb の関連部分は次のとおりです。
ActiveRecord::Schema.define(:version => 20090516204736) do
create_table "categories", :force => true do |t|
t.integer "journal_id", :null => false
t.string "name", :limit => 200, :null => false
t.integer "parent_id"
t.integer "lft"
t.integer "rgt"
end
add_index "categories", ["journal_id", "parent_id", "name"], :name => "index_categories_on_journal_id_and_parent_id_and_name", :unique => true
create_table "entries", :force => true do |t|
t.integer "journal_id", :null => false
t.string "title", :null => false
t.string "permaname", :limit => 60, :null => false
t.text "raw_body", :limit => 2147483647
t.datetime "created_at", :null => false
t.datetime "posted_at"
t.datetime "updated_at", :null => false
end
create_table "entry_categories", :force => true do |t|
t.integer "entry_id", :null => false
t.integer "category_id", :null => false
end
add_index "entry_categories", ["entry_id", "category_id"], :name => "index_entry_categories_on_entry_id_and_category_id", :unique => true
end
また、カテゴリを使用してエントリを保存すると、更新アクションで (を呼び出して@entry.attributes = entry_params
) 正常に機能するため、問題は EntryCategory レコードが作成されようとした時点でエントリが存在しないことにのみ基づいているように思えます。