yaru
yaru

Reputation: 1310

How to make Active Record associations work without creating a foreign_key?

I want an item to be able to get an associated record from ItemType table:

item = Item.first

item.item_type # <--- ERROR

But I get an error:

SELECT "item_types".* FROM "item_types" WHERE "item_types"."item_id" = ? LIMIT 1 [[nil, 11]] SQLite3::SQLException: no such column: item_types.item_id: SELECT "item_types".* FROM "item_types" WHERE "item_types"."item_id" = ? LIMIT 1 ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: item_types.item_id: SELECT "item_types".* FROM "item_types" WHERE "item_types"."item_id" = ? LIMIT 1

From error I can see that ActiveModel tries to access item_id column. But I do not want to create an item_id column inside my ItemType table... It is an enumeration table with types of items such as:

#id|name

1|"Task"
2|"User Story"
3|"Bug"
4|"Feature Request"

Item model

#
# Table name: items
#
#  id           :integer          not null, primary key
#  name         :string
#  created_at   :datetime         not null
#  updated_at   :datetime         not null
#  item_type_id :integer
#

class Item < ActiveRecord::Base
    has_one :item_type
end

ItemType model

# == Schema Information
#
# Table name: item_types
#
#  id         :integer          not null, primary key
#  name       :string
#  created_at :datetime         not null
#  updated_at :datetime         not null
#

class ItemType < ActiveRecord::Base
end

Upvotes: 1

Views: 57

Answers (1)

zwippie
zwippie

Reputation: 15515

You have only defined the relationship in model Item but you have to define it in model ItemType too:

class ItemType < ActiveRecord::Base
  has_many :items
end

Upvotes: 2

Related Questions