आप मॉडल aasm_state setter (या मेरे उदाहरण में स्थिति) को ओवरराइड कर सकते हैं ताकि यह ईवेंट नाम स्वीकार कर सके। फिर हम यह देखने के लिए जांचते हैं कि यह एक वैध घटना है या नहीं, यह देखने के लिए जांचें कि संक्रमण वैध है या नहीं। यदि वे नहीं हैं तो हम सही त्रुटि संदेश जोड़ते हैं।
एक अनुरोध कल्पना
it "should cancel" do
put "/api/ampaigns/#{@campaign.id}", {campaign: {status: "cancel"}, format: :json}, valid_session
response.code.should == "204"
end
मॉडल युक्ति
it "should invoke the cancel method" do
campaign.update_attribute(:status, "cancel")
campaign.canceled?.should be_true
end
it "should add an error for illegal transition" do
campaign.update_attribute(:status, "complete")
campaign.errors.should include :status
campaign.errors[:status].should == ["status cannot transition from pending to complete"]
end
it "should add an error for invalid status type" do
campaign.update_attribute(:status, "foobar")
campaign.errors.should include :status
campaign.errors[:status].should == ["status of foobar is not valid. Legal values are pending, active, canceled, completed"]
end
मॉडल
class Campaign < ActiveRecord::Base
include AASM
aasm column: :status do
state :pending, :initial => true
state :active
state :canceled
state :completed
# Events
event :activate do
transitions from: :pending, to: :active
end
event :complete do
transitions from: :active, to: [:completed]
end
event :cancel do
transitions from: [:pending, :active], to: :canceled
end
end
def status=(value)
if self.class.method_defined?(value)
if self.send("may_#{value}?")
self.send(value)
else
errors.add(:status, "status cannot transition from #{status} to #{value}")
end
else
errors.add(:status, "status of #{value} is not valid. Legal values are #{aasm.states.map(&:name).join(", ")}")
end
end
end
ध्यान दें कि इस मामले में आप से राज्य में "x" के लिए "एक संक्रमण नहीं हो सकता प्रकाशित "और एएएसएम एक अपवाद उठाएगा। अन्यथा, उचित लगता है। लड़का, मैं आज सुबह एक नाइटपीकर हूं: पी – jaydel
ठीक है, यह छद्म कोड है। यह केवल एक सामान्य पैटर्न को चित्रित करने के लिए है। – Wukerplank