has_many :through でビルドを使用する
-
21-08-2019 - |
質問
を持っています 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
そして 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レコードを作成しようとした時点でエントリが存在しないことだけに基づいているように思えます。
解決
このエラーの原因を突き止めたところ、 nested_has_many_through
プラグイン。私がインストールしたバージョンにはバグがあったようです。最新バージョンに更新すると、ビルドが再び動作するようになりました。
他のヒント
なぜ電話するのですか
self.journal.build(entry_params)
の代わりに
Entry.new(entry_params)
@journal を指定して、特定のジャーナルに関連付けられた新しいエントリを作成する必要がある場合は、次のようにします。
@yournal.entries.build(entry_params)