Rails外键不适用于一个habtm关系?

时间:2013-08-08 13:52:06

标签: ruby-on-rails rails-migrations

我的模型看起来像:

    class Location < ActiveRecord::Base
  attr_accessible :title
  has_and_belongs_to_many :adjacent_locations, :class_name => "Location", :foreign_key => "adjacent_location_id", :join_table => "adjacent_locations_locations"
  has_many :npcs #who are currently in this location
  has_and_belongs_to_many :expected_npcs, :class_name => "Npc" #who do I expect to be here (is it their house?)
  has_and_belongs_to_many :items  #what do I actually have?
  has_and_belongs_to_many :expected_items, :class_name => "Item"
  has_and_belongs_to_many :expected_item_types, :class_name => "ItemType", :foreign_key => "e_item_type_id", :join_table => "e_item_types_locations"
end

除了“expected_item_types”之外,其中每一个has_and_belongs_to_many都有效。

它看起来就像模型中的相邻位置,但不起作用。

我的迁移运行得很好,就我所知,它看起来与其他连接表完全一样:

class CreateEItemTypesLocationsTable < ActiveRecord::Migration
    def self.up
    create_table :e_item_types_locations, :id => false do |t|
        t.references :e_item_type
        t.references :location
    end
    add_index :e_item_types_locations, [:e_item_type_id, :location_id], :name => "eit_loc"
  end

  def self.down
    drop_table :e_item_types_locations
  end
end

它有一个像expected_items一样的命名索引,并且模型中的外键就像Location一样。设置带有命名索引的外键时有什么特别的事吗?

我得到的实际错误是

SQLite3::SQLException: no such column: e_item_types_locations.item_type_id: SELECT "item_types".* FROM "item_types" INNER JOIN "e_item_types_locations" ON "item_types"."id" = "e_item_types_locations"."item_type_id" WHERE "e_item_types_locations"."e_item_type_id" = 1

这意味着它完全无视我设置的外键......这有什么明显的错误吗?

编辑:我想我至少想到了它的一部分,而不是外键,它应该是“association_foreign_key”。但是......那么......为什么我不必为adjacent_locations做那个?是因为他们与他们所在的模特属于同一类吗?

1 个答案:

答案 0 :(得分:0)

看起来我对expected_item_types字段需要“association_foreign_key”而不是“foreign_key”。有人知道为什么我不需要它为“adjacent_locations”字段吗?