当创建下面的对象“Machine”时,得到ActiveRecord :: AssociationTypeMismatch Component(#70354292616060) expected, got String(#70354278277000)
;ActiveRecord :: AssociationTypeMismatch创建新时
目标:尝试将“属性”分配给引用其他模型的模型。
问题:我想听取专家的意见,这种手术的最佳做法是什么。
设置:
导轨3.2.12 /红宝石1.9.3-P194:
型号:
class Machine < ActiveRecord::Base
attr_accessible :cpu, :name, :ram
belongs_to :cpu, class_name: "Component", foreign_key: "component_id"
belongs_to :ram, class_name: "Component", foreign_key: "component_id"
end
class Component < ActiveRecord::Base
attr_accessible :name
has_many :machines
end
查看用于机器:
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :cpu %><br />
<%= f.collection_select :cpu, Component.all, :id, :name %>
</div>
<div class="field">
<%= f.label :ram %><br />
<%= f.collection_select :ram, Component.all, :id, :name %>
</div>
<div class="actions">
<%= f.submit %>
</div>
程序 :
- 创建于组件几个对象,使得
id:1 name:"cpu1"
&id:2 name:"ram1"
- 转到machines_path并从下拉选择CPU1及RAM1下来
- 了以下错误创建机器时提交
Component(#70354292616060) expected, got String(#70354278277000)
我尝试改变:cpu和:ram在View中:cpu_id和:ram_id。之后,我可以无误地创建模型。但是我无法直接从机器访问cpu & ram;
1.9.3-p194 :001 > Machine.first
Machine Load (0.1ms) SELECT "machines".* FROM "machines" LIMIT 1
=> #<Machine id: 2, name: "test", cpu_id: 1, ram_id: 1, created_at: "2013-05-06 16:42:47", updated_at: "2013-05-06 16:42:47">
1.9.3-p194 :002 > Machine.first.cpu
Machine Load (0.2ms) SELECT "machines".* FROM "machines" LIMIT 1
=> nil
1.9.3-p194 :003 > Machine.first.ram
Machine Load (0.2ms) SELECT "machines".* FROM "machines" LIMIT 1
=> nil
所以我不得不创建以下模型方法
class Machine < ActiveRecord::Base
(snip)
def cpu
Component.find_by_id(self.cpu_id)
end
def ram
Component.find_by_id(self.ram_id)
end
然后我就可以得到预期的输出
1.9.3-p194 :002 > Machine.first.cpu.name
Machine Load (0.2ms) SELECT "machines".* FROM "machines" LIMIT 1
Component Load (0.2ms) SELECT "components".* FROM "components" WHERE "components"."id" = 1 LIMIT 1
=> "CPU1"
但我觉得这是多余的,找一个更简单的方法来做到这一点。
欣赏是否有任何建议。
您应该看看nested_attributes;) – MrYoshiji 2013-05-06 17:06:43
谢谢MrYoshiji对于你的建议,会试试看。 – charles 2013-05-06 17:49:26