2009-06-29 40 views
1

我有一个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. 

注意,在第二行以“#”是逐字;它不输出对象。

我已经尝试将表单上的我的类别选择框命名为categoriescategory_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记录被尝试创建的条目。

+0

请问您可以附上schema.rb的定义吗? – 2009-06-30 07:12:13

回答

2

我追踪到这个错误的原因是在nested_has_many_through插件。看来,我安装的版本是越野车;在更新到最新版本后,我的构建再次运行。

1

你为什么叫

self.journal.build(entry_params) 

,而不是

Entry.new(entry_params) 

如果你需要创建对应特定的杂志新的项目,给予@journal,你可以做

@yournal.entries.build(entry_params) 
+1

它实际上是@ journal.entries.build,我在输入问题时搞砸了,谢谢指出。 – 2009-06-30 03:33:31