【发布时间】:2014-03-07 02:41:25
【问题描述】:
我正在尝试解决我在 rails 4 中的 belongs_to 关系:我有三个表 - 一个 hardware 表、一个 entity 表和一个 replacement 表。 entities是一个视图:
db=> \d entities;
View "public.entities"
Column | Type | Modifiers
-------------+---------+-----------
id | integer |
device | text |
entity_type | text |
serial | text |
我用迁移创建另外两个:
class CreateHardwares < ActiveRecord::Migration
def change
create_table :hardwares do |t|
t.string :vendor
t.string :model
t.decimal :price
end
end
end
class CreateReplacements < ActiveRecord::Migration
def change
create_table :replacements do |t|
t.belongs_to :entity
t.belongs_to :hardware
t.integer :quantity
t.belongs_to :replacement_hardware
end
end
end
所以基本思想是replacement 指的是一个实体(如电脑)。它还保存其(当前)hardware 和实体的替换 hardware 的信息。
class Entity < ActiveRecord::Base
self.primary_key = "id"
has_one :replacement
end
class Hardware < ActiveRecord::Base
end
class Replacement < ActiveRecord::Base
belongs_to :entity
belongs_to :hardware
belongs_to :replacement_hardware, class_name: "Hardware", :foreign_key => 'replacement_hardware_id'
end
所以我用一些东西填充表并尝试查询:
Replacement.includes(:entity).where(:id=>1)
Replacement Load (0.7ms) SELECT "replacements".* FROM "replacements" WHERE "replacements"."id" = 1
Entity Load (2.4ms) SELECT "entities".* FROM "entities" WHERE "entities"."id" IN (35692)
=> #<ActiveRecord::Relation [#<Replacement id: 1, entity_id: 35692, entity_type: nil, hardware_id: nil, quantity: nil, replacement_hardware_id: nil, created_at: nil, updated_at: nil>]>
好的,看起来不错.. 但是,当我尝试访问关联 entity 时,它会引发错误:
Replacement.includes(:entity).where(:id=>1).entity
NoMethodError: Replacement Load (0.6ms) SELECT "replacements".* FROM "replacements" WHERE "replacements"."id" = 1
Entity Load (3.8ms) SELECT "entities".* FROM "entities" WHERE "entities"."id" IN (35692)
undefined method `entity' for #<Replacement::ActiveRecord_Relation:0x007fb156f6e758>
【问题讨论】:
标签: model ruby-on-rails-4 foreign-keys belongs-to