Вместо этого вам нужно проверить $?
, что является статусом выхода предыдущей команды. passwd
завершает работу с 0, если все работает нормально и не равно нулю, если сбой пароля не был выполнен (неправильный пароль, несоответствие пароля и т. д.)
passwd
while [ $? -ne 0 ]; do
passwd
done
С вашей версией backtick вы сравнивая вывод passwd, который будет выглядеть как Enter password
и confirm password
и т. п.
Если вы хотите сослаться на предыдущие изменения в объектах ActiveRecord (после того, как изменения сохранятся и объект будет перезагружен), я рекомендую создать отдельную таблицу (например, product_dirties
) для отслеживания указанных изменений. Давайте используем вашу модель Product
в качестве примера:
Сначала вы захотите создать таблицу product_dirties
create_table :product_dirties do |t|
t.references :product, index: true, foreign_key: true
t.jsonb :modifications
end
Затем добавьте модель ProductDirty
class ProductDirty < ApplicationRecord
belongs_to :product, inverse_of: :product_dirties
validates_presence_of :product, :modifications
end
И обновите свою модель Product
, чтобы включить новую ассоциацию и обратный вызов для создания грязных записей при внесении изменений:
class Product < ApplicationRecord
has_many :product_dirties, inverse_of: :product
before_save :create_dirty_record, if: -> { changed? }
private
def create_dirty_record
# modifications will be saved in this format: {"name"=>"new name here!"}
attribute_changes = ActiveSupport::HashWithIndifferentAccess[self.changed.map{ |attr| [attr, self.method(attr).call] }]
if attribute_changes.present?
ProductDirty.find_or_create_by(product: self).update_attribute(:modifications, attribute_changes)
end
self.restore_attributes # <- add this if you'd like to revert the changes to the product and keep them separate in the `product_dirties` table
end
end
Затем вы можете добавить метод в свой Product
модель, которая делает поиск изменений. Мы добавили метод apply_dirty_record
(см. Ниже) к нашей родительской модели (например, Product
), так как мы фактически не сохраняем изменения (см. Примечание рядом с self.restore_attributes
выше).
def apply_dirty_record
dirty_record = ProductDirty.find_by(product: self)
self.assign_attributes(dirty_record.modifications) if dirty_record
end