Model rails 4属于关系,关联结果为NoMethodError
我试图在rails 4中计算出我的Model rails 4属于关系,关联结果为NoMethodError,model,ruby-on-rails-4,foreign-keys,belongs-to,Model,Ruby On Rails 4,Foreign Keys,Belongs To,我试图在rails 4中计算出我的所属关系:我有三个表-一个硬件表,一个实体表和一个替换表实体是一个视图: db=> \d entities; View "public.entities" Column | Type | Modifiers -------------+---------+----------- id | integer | device | text | entity_type | text |
所属关系:我有三个表-一个硬件
表,一个实体
表和一个替换
表<代码>实体
是一个视图:
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.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>]>
我认为你应该多读一些关于联想的书。如果您定义了一个归属关系,您还应该将相应的ID添加到迁移中 例如,如果替换项属于某个实体,则在替换项表中应该有实体id。否则,替换不知道其关联。一旦你做到了这一点,你就可以实际调用关系
另外一些注意事项:您不必将id定义为实体中的主键。遵循约定,仅当主键与默认值不同时才定义主键。您的实体模型也没有定义任何关系。关系是双向的,应该这样定义。Duh!只是为了回答我自己的问题,以便我可以再次搜索它(以防我愚蠢到重复我的错误)。。。它基本上归结为
where
语句。由于其中
返回一个对象数组,它当然不知道什么是实体
。因此,将其放入循环中或先执行
将按预期工作!即
Replacement.includes(:entity).where(:id=>1).first.entity
或
从postgres输出来看,我的
replacements
表中确实有实体id
(在这些注释中输入有点困难)。另外,ownerto\u to
migration语句不是为我创建的吗?如果以后定义了关系,就不会了。无论如何,更新了我的答案以提供更多信息。
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>
Replacement.includes(:entity).where(:id=>1).first.entity
Replacement.includes(:entity).where(:id=>1) do |r|
r.entity
end