简体   繁体   中英

Rails Foreign Key not working for one habtm relation?

My model looks like:

    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

every single one of those has_and_belongs_to_many works except "expected_item_types".

It looks JUST like the adjacent locations in the model, but does not work.

My migration runs just fine, and looks exactly like the other join tables as far as I can tell:

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

It has a named index just like expected_items does, and a foreign key in the model just like Location does. Is there something special to do when setting a foreign key with a named index?

The actual error I'm getting is

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

Which implies it's just COMPLETELY ignoring the foreign key I set... Is there anything obviously wrong with this?

Edit: I think I figured out at least part of it, instead of foreign key, it should be "association_foreign_key". But...then...why didn't I have to do that for the adjacent_locations? Was it because they were of the same class as the model they were in?

Looks like I needed "association_foreign_key" instead of "foreign_key" for the expected_item_types field. Anybody know why I didn't need it for the "adjacent_locations" field?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM