Reputation: 1362
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?
Upvotes: 0
Views: 271
Reputation: 48490
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:
after_validation_on_create :toggle_other_table_asset
def toggle_other_table_asset
if self.in_use
sibling.in_use = 1
else
sibling.in_use = 0
end
sibling.save
end
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.
Upvotes: 1
Reputation: 66445
You can connect to multiple databases using rails as explained here. But to me if you just want to replicate data, it might be simpler to have some logic on the database level and leave rails out of it.
Upvotes: 0