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

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

我试图命名我的类别选择框的形式上categoriescategory_ids但既不有所作为;如果任是在entry_params,保存操作将失败。如果没有选择的类别,或予删除categoriesentry_params@entry_attrs.delete(:category_ids),保存工作正常,但类别不保存,很明显。

在我看来,这个问题是一个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)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top