我有一个Entry
模型和Category
模型,如果一个条目中有许多分类(通过EntryCategories
):使用构建具有的has_many:通过
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
中,保存将失败。如果未选择类别,或者我从entry_params
(@entry_attrs.delete(:category_ids)
)中删除categories
,则保存工作正常,但类别显然不保存。
在我看来,问题是entry条目记录试图在保存条目记录之前进行?不应该建立照顾?
更新:
这里的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记录被尝试创建的条目。
请问您可以附上schema.rb的定义吗? – 2009-06-30 07:12:13