I have two tables. One named "instruction" and the other named "message".
Both of these tables contain a "inactive" field which is a boolean.
In the instruction table there is also a metadata field that contains "message_id" (This is the id of the unique record in the message table).
The message table already had the inactive field setup and the relevant records are either 1 for true or 0 for false. E.g. 1 If inactive or 0 if active.
I have also added the same field to the instruction table. I am trying to update the inactive field on this table based on the value of the inactive field in the message table, through the use of the message_id. Preferably through Ruby. How would I go about this?
I understand that through the use of the message_id I have access to the message table. However, I don't understand how to update the inactive field based on the inactive field in the other table.
CodePudding user response:
From what you described, I can understand your models files are something like this:
Instruction
class Instruction
belongs_to :message
end
Message:
class Message
has_many :instructions
end
My suggested solution for your problem is using the callbacks of rails, in this case I would choose the after_save
callback. You can also find other interesting callback here https://guides.rubyonrails.org/active_record_callbacks.html, hope it helps:
class Message
has_many :instructions
after_save :update_instructions_inactiveness, if: -> { inactive_changed? }
def update_instructions_inactiveness
instructions.update_all(inactive: self.inactive)
end
end