Claudi
Claudi

Reputation: 5416

Is data integrity important when using Ruby on Rails ActiveRecord's associations?

I'm just playing with RoR and I've noticed that ActiveRecord associations such as has_many or belongs_to are decoupled from the database running behind, i.e., these association are set regardless of the the constraints set by the database. For example, I have a table comments and a table users and they are related through has_many and belongs_to statements (a comment belongs to a user and a user has many comments). However these associations still let me assign a comment to a, for example, non-existing user. The reason of this is that there's no foreign key defined in the database.

My question is: should I just rely on ActiveRecord's associations to handle data integrity or should I also add foreign keys in migration files?

Thank you.

Upvotes: 0

Views: 227

Answers (2)

TarunJadhwani
TarunJadhwani

Reputation: 1161

You have to add foreign keys to migration file to make your associations work correctly. With reference to the example mentioned, you have to add an attribute user_id to comments table. For more information on how Active Record Associations work, follow this rails guide.

Upvotes: 0

roman-roman
roman-roman

Reputation: 2796

Rails holds some conventions that enforcement of data integrity should be done in the application, not in the database.

To keep data integer on application-level, you can use model validations to enforce the presence of associations.

Upvotes: 1

Related Questions