I have two tables from the same DB that when one field is updated, a corresponding field needs to be updated in the second table with that information. How can I connect those fields (and tables) together using the Rails framework?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
If you would like to handle this on the Rails stack itself, one way I currently handle a similar situation is using an ActiveRecord Callback method. Documentation for that is available here. In your model where the attribute is originally being modified you could use the after_validation_on_create callback:
You also might want to consider using an ActiveRecord transaction to ensure the integrity of your data, more information is found here.
The best piece of advice I can give you is to consider the potential drawbacks to ensuring everything is done on the application layer. There’s also drawbacks involved in coupling your data in this fashion. Perhaps you should think about refactoring your models to avoid duplication of data.
Examples of where things can go wrong include maintenance scripts which run on the weekends that clean up your database, or interacting with your underlying database’s command line interface and modifying the culprit attributes manually.. without having a database TRIGGER programmed, you’re running the risk of damaging the integrity of your data.