I’m not sure the title really explains correctly what i’m trying to do so forgive me. I have a table called clients for an invoicing system i’ve built. I also have tables called projects and invoices.
Here’s an example (not the actual columns in the tables, just for an example) of my database structure.
Clients
id
name
description
archive
Projects
id
client_id
name
description
archive
Projects
id
client_id
project_id
name
description
archive
I have created the ability to archive a given invoice, project, or client independently. However, i wanted to see what the best way to do this would be if i wanted to have say the projects and invoices for a client to be automatically marked as archived when i archive the client. My process would be this:
- Archiving a client would archive the client, all projects with that client id, and all invoices with that same client id.
- Archiving a project would archive the project and all invoices with that project id.
- Archiving an invoice just archives the invoice itself
NOTE: by “archived” i mean the archive bit gets flipped to 1 instead of 0 (not archived / active).
By the way, the way that you archive something is on the edit screen there is an “Archive?” checkbox that you would check off to archive the item.
I know that in my edit action in my controller i can just say something like if archive == 1 then run additional sql update statements to update dependent items else @object.save to just save the data for the edited item.
My question?
Is there a better way to do this? Is the way i mentioned generally the best practice? I am already using :dependent => :destroy elsewhere in the model to delete rows in associated tables when a “parent” item is deleted. Is there something pre-built in to Rails that will allow me to mark things like i am trying to do through the relationships of the tables?
Thanks for any help with this! Hope i explained the problem and question well enough, but let me know if you have questions.
A better way would be to create a
after_updateon theClientandProjectmodel :So when you save a client, the
archive_checkis triggered. And then if archived, it’ll update all the relatedprojects. Since you update theprojects, thearchive_checkwill also be triggered in theProjectmodel for each invoice this time.