使用带有has_many的构建:通过

时间:2009-06-29 20:59:13

标签: ruby-on-rails has-many-through

我有一个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),则保存工作正常,但显然不会保存类别。

在我看来,问题是在保存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记录点上不存在的条目试图创造。

2 个答案:

答案 0 :(得分:2)

我将此错误的原因记录在nested_has_many_through插件中。似乎我安装的版本是错误的;更新到最新版本后,我的构建再次工作。

答案 1 :(得分:1)

你为什么打电话

self.journal.build(entry_params)

而不是

Entry.new(entry_params)

如果您需要创建与特定期刊关联的新条目,给定@journal,您可以

@yournal.entries.build(entry_params)
相关问题