2

我目前正在开发一个基于现有数据库的新应用程序,使用 DataMapper 进行数据访问。但是,它在处理外键时的约定不是数据库使用的。

例子:

class Invoice
  include DataMapper::Resource

  storage_names[:default] = 'invoices'

  property :id, Serial
  # ... more properties ...

  has n, :items
end

class Item
  include DataMapper::Resource

  storage_names[:default] = 'invoiceItems'

  property :id, Serial
  # ... more properties ...

  belongs_to :invoice  # this should use 'invoiceId' instead of 'invoice_id'
end

有什么办法可以让 DataMapper 使用的外键成为“invoiceId”而不是它目前尝试使用的“invoice_id”(如上面的评论所示)?我知道这可以通过添加普通字段来完成,:field => 'fieldName'但我发现没有这样的关联方式。

4

1 回答 1

5

并且不是第一次,感谢 Jan De Poorter非常有用的博客条目,我找到了自己问题的答案。

在处理字段名称时有必要调整约定,以便它只使用符号的名称,而不是使用它关于下划线的内置智能。

repository(:default).adapter.field_naming_convention = lambda { |value| value.name.to_s }

然后可以按如下方式指定外键名称:

class Invoice
  # bla bla...
  has n, :items, :child_key => [:invoiceId]
end

class Item
  # bla bla...
  belongs_to :invoice, :child_key => [:invoiceId]
end

值得注意的是(如上图),需要在关系的两边指定键名(我觉得有点奇怪,但是嘿嘿)。希望这将帮助其他发现自己问同样问题的人。感谢Jan De Poorter的回答。

于 2010-01-01T12:50:53.070 回答