Foreign key name in DataMapper associations
I'm currently working on a new app based around an existing database, making use of DataMapper for the data access. However, its conventions when dealing with foreign keys are not what the database uses.
Example:
class Invoice
include DataMapper::Resource
storage_names[:default] = 'invoices'
property :id, Serial
# ... more properties ...
has n, :items
end
class Item
include DataMapper::Resourc开发者_JAVA百科e
storage_names[:default] = 'invoiceItems'
property :id, Serial
# ... more properties ...
belongs_to :invoice # this should use 'invoiceId' instead of 'invoice_id'
end
Is there any way I can get the foreign key used by DataMapper to be 'invoiceId' rather than the 'invoice_id' it tries to use at the moment (as indicated by the comment above)? I know this can be done with normal fields by adding :field => 'fieldName'
but I have found no such way for associations.
And not for the first time, I have found the answer to my own question thanks to Jan De Poorter's very helpful blog entry.
It is necessary to adjust the conventions when dealing with field names so that it simply uses the name of the symbol rather than using it's built-in smarts regarding underscores.
repository(:default).adapter.field_naming_convention = lambda { |value| value.name.to_s }
The foreign key name can then be specified as follows:
class Invoice
# bla bla...
has n, :items, :child_key => [:invoiceId]
end
class Item
# bla bla...
belongs_to :invoice, :child_key => [:invoiceId]
end
It is worth noting (as shown above) that the key name needs to be specified on both sides of the relationship (which I find a little bit strange, but hey). Hopefully this will help anyone else who finds themselves asking the same question. Thanks to Jan De Poorter for the answer.
精彩评论