Ryan Ferretti
Ryan Ferretti

Reputation: 2961

Is it good practice to set a custom id value for an ActiveRecord object

I am writing a simple rails app that caches values from a web service. The web service returns a list of objects that look like this:

<objects>
    <object>
        <id>12345</id>
        <name>obj name</name>
    </object>
    ....
</objects>

Is it okay to use the id coming in as the id for my ActiveRecord object if I am guaranteed it is unique... or is it better practice set it as a different attribute and let ActiveRecord handle the id? I have read through the code and it looks like the create method on ActiveRecord does not generate a new id if it is already set. Am I understanding this correctly?

Thanks

Upvotes: 2

Views: 744

Answers (2)

Toby Hede
Toby Hede

Reputation: 37133

I would definitely use my own id, simply because when allowing external access there are no guarantees.

Upvotes: 0

jonnii
jonnii

Reputation: 28312

If your id field is set to autoincrement you won't be able to specify it, at least not easily. However this is dependent on your database.

I suggest storing external ids independently from your own ids. In the long run it'll give you more flexibility and isolation from the third party's id scheme changing.

Upvotes: 2

Related Questions