【发布时间】:2011-03-31 16:46:44
【问题描述】:
我一直在看这个:
http://datamapper.org/docs/find
虽然我知道这很简单,但我无法看到我正在寻找的东西。
我有两张表格,分别是scans 和stations,以及相关字段:
STATIONS - id (primary key), name
SCANS - id (primary key), item_id, in_station, out_station
其中in_station 和out_station 是stations 表中id 字段的外键。
我有一个Scan 对象
class Scan
include DataMapper::Resource
property :id, Integer, :key => true
property :item_id, Integer
property :in_station, Integer
property :out_station, Integer
end
所以现在,我可以使用Scan.all(:item_id => @barcode) 来获取特定项目的所有扫描,并且我有in_station id 和out_station id。但是,获取 names 而不是 id 的最佳方式是什么。我认为这比每次扫描调用Station.get(:id=> scan.in_station) 都要容易。
这很容易使用 SQL,但是我如何更改 Scan/Station 以获取名称或拥有一个作为 Station 对象的属性,以便我可以执行 scan.station.name 之类的操作?
编辑:
我几乎已经完成了这项工作。我有一个 Station 课程:
class Station
include DataMapper::Resource
property :id, Integer, :key => true
property :name, String
end
我在Scan 中删除了property :in_station 和property :out_station 并替换为:
belongs_to :in_station, :model => 'Station', :child_key => 'id'
belongs_to :out_station, :model => 'Station', :child_key => 'id'
我认为/希望是说“有一个名为 in_station 的字段是 Station 表的外键,而一个名为 out_station 的字段是相同的”。事实上,in_station 和 out_station 现在是 Station 的实例,但是,它们是对象。即使 in_station 和 out_station 是不同的值,我在每次扫描时都会得到相同的对象。我做错了什么,我怎么能指出 in_station 和 out_station 都是对 Station 的引用,但是当它们的 id 不同时,我期望不同的对象。
【问题讨论】:
-
查看在数据库中为扫描表创建的字段。就像我在下面所说的那样,尽管名称“child_key”暗示了其他情况,但您需要使用如下所示的名称。你的
belongs_to行说的是“扫描属于一个名为‘in_station’的站,并将加载一个与名为id的扫描属性匹配的id的站。”那不是你想要的。您希望“扫描属于具有名为 'in_station' 的关联的工作站,并将加载具有与名为in_station_id的扫描属性匹配的id的工作站。”
标签: ruby-on-rails ruby datamapper