我有一个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.
请注意,第二行的“#”是逐字记录的;它不输出对象。
我尝试将表单上的类别选择框命名为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 记录时不存在的条目。