使用DataMapper获取记录

时间:2011-03-30 20:00:20

标签: ruby datamapper

第一次使用DataMapper。我在MySQL数据库中设置了一个表并连接到它。我已经定义了以下映射:

class Track_Scan
    include DataMapper::Resource

    property :item_id,                  Integer
    property :current_station_id,       Integer
    property :next_station_id,          Integer
end

它返回正确的数字项目 - 例如如果数据库中有五个记录用于给定的id,Track_Scan.all(:item_id => my_id)将产生一组五个对象 - 但是当我在这个上调用每个对象时,我会看到同一个对象五次:

#<Track_Scan:0x7fcbcfca59c0>
#<Track_Scan:0x7fcbcfca59c0>
#<Track_Scan:0x7fcbcfca59c0>
#<Track_Scan:0x7fcbcfca59c0>
#<Track_Scan:0x7fcbcfca59c0>

而不是五个不同的对象在current_station_idnext_station_id中具有不同的值,就像他们在表格中实际做的那样。

任何帮助?

1 个答案:

答案 0 :(得分:1)

您的模型缺少钥匙。如果要使用复合键,则需要执行以下操作:

class Track_Scan
  include DataMapper::Resource

  property :item_id,            Integer, :key => true
  property :current_station_id, Integer, :key => true
  property :next_station_id,    Integer, :key => true
end

此外,在您需要所有型号后,您需要致电:

DataMapper.finalize

希望这有帮助