Skip to content

Instantly share code, notes, and snippets.

@Sephyros
Last active November 26, 2015 13:22
Show Gist options
  • Save Sephyros/9908fe1c77b6e36a90ee to your computer and use it in GitHub Desktop.
Save Sephyros/9908fe1c77b6e36a90ee to your computer and use it in GitHub Desktop.
Moving next state with validation on STI
class Order < ActiveRecord::Base
end
class WaitingOrder < Order
def cancel_order(params)
params = params.merge(type: CanceledOrder.to_s)
update_attributes(params)
end
end
class CanceledOrder < Order
validates :justification, presence: true
end
class WaitingOrderTest < ActiveSupport::TestCase
test "should cancel waiting order" do
p = { justification: nil }
f = WaitingOrder.new
assert_not f.cancel_order(p)
assert_equal 'WaitingOrder', f.type
assert f.errors[:justification].include?(I18n.t('activerecord.errors.messages.blank'))
p = { justification: 'Too late!' }
assert f.cancel_order(p)
assert_equal 'CanceledOrder', f.type
end
end
@Sephyros
Copy link
Author

class Order < ActiveRecord::Base
  validates :justification, presence: true, if: :is_canceled?

  def is_canceled?
    type == "CanceledOrder"
  end
end

class WaitingOrder < Order
  def cancel(params)
    params = params.merge(type: CanceledOrder.to_s)
    update_attributes(params) if params[:justification].present?
  end
end

class CanceledOrder < Order
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment